Search code examples
c++c++14move-semanticsnrvo

Avoid const locals that are returned?


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?


Solution

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