Is it possible for a non-member function to return a const value?

后端 未结 2 1230
闹比i
闹比i 2021-01-27 01:35

If so, how? Does this question even make sense?

In my case it would make no sense to have the returned object modified by the caller, so I want to mark it as non-modifia

2条回答
  •  失恋的感觉
    2021-01-27 01:47

    const MyClass foo(); is valid, but returning a const value doesn't make sense - it's copied anyway.

    You can return e.g. a const reference: const MyClass & foo(); is also perfectly valid. This doesn't prevent the user from making a copy though.

    If you're thinking about const MyClass * foo(); then the const is more meaningful - the user will not be able to modify the pointed to MyClass instance.

提交回复
热议问题