What is the point in returning a const?

Can anybody provode me with an example about the use of const return type and how exactly it os useful?
There is not much of a point in returning a const by value.

For an example of returning a reference to const, see (the const overload of) std::vector<>::front() const
http://en.cppreference.com/w/cpp/container/vector/front

In a const vector, the elements are not modifiable. In a non-const vector, they are.
To return a const pointer is a by value example:
http://en.cppreference.com/w/cpp/container/vector/data

EDIT: my bad,
1
2
3
4
5
const T * foo()
// is a
U * foo()
// not a
const V foo()
Last edited on
Returning a const pointer by value is a terrible example.
The compiler is required to ignore the const-qualifier on the scalar return type.

Also note that std::vector<>::data() returns a non-const pointer (to const) by value.

1
2
3
4
5
6
// return const pointer to const T by value
const T* const foo() ; //  bad; avoid (drop the const, it is ignored anyway)
// heed the warning: const-qualifier ignored on function return type

// return non-const pointer to const T by value
const T* bar() ; // fine; we are returning a non-const object by value 


C++ Core Guidelines say, in F.20 https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-out

It is not recommended to return a const value. Such older advice is now obsolete; it does not add value, and it interferes with move semantics.

The argument for adding const to a return value is that it prevents (very rare) accidental access to a temporary. The argument against is prevents (very frequent) use of move semantics.


the "older advice" refers to, I believe, pre-C++11 Scott Meyers who recommended returning const class objects to block non-const member function calls on temporaries (which are actually not always a bad idea)
Last edited on
Topic archived. No new replies allowed.