简体   繁体   中英

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

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-modifiable.

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

You can return eg 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.

It can be done, but doesn't necessarily make a lot of sense. If you return something by value, what the caller receives is a temporary copy of what you returned, so they normally can't modify it anyway.

It can make more sense when you're returning a reference; if (for example) you receive something by reference, and return a reference to the same, you probably want to const-qualify what you return if what you received was const-qualified. This typically means overloading your function for const/non-const parameter, each with matching return type.

Edit: This can deal with (for example) a problem that arose in C with functions like strstr and strchr , which take a const-qualified pointer, but return a pointer into the same data (string, in this case) that's not const-qualified. In C, these form a hole in the type system, where you can accidentally modify (or at least try to) something that was intended to be const, without any (visible) cast.

char *s = strchr("Mystring", 'i');
*s = 'b'; // UB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM