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

Viewed 2559
#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 Answers

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 {};
}
Related