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

5.2k views Asked by At
#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?

2

There are 2 answers

1
Jarod42 On BEST ANSWER

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.

0
eerorika On

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

Simply remove std::move. It doesn't do any thing useful here, but does prevent eliding the move.

If I write return s;, I feel uncertain whether NRVO will be executed.

How to ease the feel of uncertainty?

NRVO is never guaranteed. Best you can do to ease the uncertainty is to compile and see whether the move was elided. In practice, I would trust any modern compiler to do this NRVO as long as optimisation is enabled.

If you want to be really certain about avoiding any move, then return a prvalue rather than an lvalue. This is guaranteed to be elided since C++17:

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