I always thought that it's good to have const locals be const
void f() {
const resource_ptr p = get();
// ...
}
However last week I watched students that worked on a C++ exercise and that wondered about a const pointer being returned
resource_ptr f() {
const resource_ptr p = get();
// ...
return p;
}
Here, if the compiler can't apply NRVO (imagine some scenario under which that is true, perhaps returning one of two pointers, depending on a condition), suddenly the const
becomes a pessimization because the compiler can't move from p
, because it's const.
Is it a good idea to try and avoid const
on returned locals, or is there a better way to deal with this?
Is it a good idea to try and avoid
const
on returned locals, or is there a better way to deal with this?
Yes. In fact if resource_ptr
is a move-only type, you will get a compile-time error if you try to return one which is const
.
This is an example of where "tried-and-true" C++98/03 advice no longer applies in C++11 and forward.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With