Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To return std::move (x) or not?

Are

std::vector<double> foo ()
{
    std::vector<double> t;
    ...

    return t;
}

and

std::vector<double> foo ()
{
    std::vector<double> t;
    ...

    return std::move (t);
}

equivalent ?

More precisely, is return x always equivalent to return std::move (x) ?

like image 325
Alexandre C. Avatar asked Apr 12 '13 21:04

Alexandre C.


People also ask

Do I need to return std :: move?

std::move is totally unnecessary when returning from a function, and really gets into the realm of you -- the programmer -- trying to babysit things that you should leave to the compiler.

When should you use std :: move?

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object.

What does move () do C++?

std::move() is a function used to convert an lvalue reference into the rvalue reference. Used to move the resources from a source object i.e. for efficient transfer of resources from one object to another. std::move() is defined in the <utility> header.

Does std :: move do a copy?

std::move is actually just a request to move and if the type of the object has not a move constructor/assign-operator defined or generated the move operation will fall back to a copy.


1 Answers

They're not equivalent, and you should always use return t;.

The longer version is that if and only if a return statement is eligible for return value optimization, then the returnee binds to rvalue reference (or colloquially, "the move is implicit").

By spelling out return std::move(t);, however, you actually inhibit return value optimization!

like image 59
Kerrek SB Avatar answered Sep 19 '22 00:09

Kerrek SB