-2

I have seen lots of discussions about using std::move on a function return value (like this), and I know it's unnecessary for these cases. But what if I want to use the std::move semantic when receiving a function output like the codes below:

std::vector<double> funcA()
{
    std::vector<double> out(10000, 0.0);
    return out;
}

int main()
{
    auto out = std::move(funcA());
    return 0;
}

Is this a good use case for std::move? My understanding is move here can avoid a copy of the returned vector, especially when the vector size is very large. Please correct me if I'm wrong. Thanks so much!

  • 5
    No, this isn't a good case. It's a pessimisation. Just return it by value and receive it by value and the copy will most likely be elided (unless you are using a very old C++ version / compiler). Here's an [example](https://godbolt.org/z/xfTMbTsab). Only one object created. No copies or moves. – Ted Lyngmo Apr 29 '21 at 21:21
  • 5
    Your code may result in a worse performance than without move. That's because the compiler will perform [copy elision](https://en.cppreference.com/w/cpp/language/copy_elision) when move is not there. – freakish Apr 29 '21 at 21:23

1 Answers1

1

Is this a good use case for std::move?

No.

In good use cases, std::move is called on an lvalue. This gives the compiler freedom to treat the value as a temporary* in most cases (but not all).

You are calling std::move on a temporary*. Telling the compiler to treat your temporary as a temporary in most cases (but not all) doesn't give new capabilities to the compiler, it takes them away.

*By "temporary", I mean prvalue.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180