c++performancec++17standardsnrvo

How to avoid the "pessimizing-move" warning of NRVO?


#include <string>

std::string f()
{
    std::string s;
    return std::move(s);
}

int main()
{
    f();
}

g++ -Wall z.cpp gives a warning as follows:

z.cpp: In function ‘std::string f()’:
z.cpp:6:21: warning: moving a local object in a return statement prevents copy elision [-Wpessimizing-move]
    6 |     return std::move(s);
      |            ~~~~~~~~~^~~
z.cpp:6:21: note: remove ‘std::move’ call

I know if I change return std::move(s); to return s;, the warning will be avoided. However, according to the C++ standard, NRVO, say in this case, is not guaranteed. If I write return s;, I feel uncertain whether NRVO will be executed.

How to ease the feel of uncertainty?


Solution

  • You should do

    std::string f()
    {
        std::string s;
        return s;
    }
    

    if NRVO doesn't apply, move is done automatically.

    See return#Automatic_move_from_local_variables_and_parameters.