Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning std::vector with std::move

Tags:

I have a very basic question: is it a good idea to return a std::vector<A> using std::move? For, example:

class A {}; std::vector<A> && func() {     std::vector<A> v;     /* fill v */     return std::move(v); } 

Should I return std::map, std::list.. etc... in this way?

like image 667
Koban Avatar asked May 19 '17 09:05

Koban


People also ask

Can you 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.

What happens when you std :: move a vector?

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. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.

How do you return a vector STD?

In C++11, this is the preferred way: std::vector<X> f(); That is, return by value. With C++11, std::vector has move-semantics, which means the local vector declared in your function will be moved on return and in some cases even the move can be elided by the compiler.

Can you return a vector C++?

Yes, a function can return a vector in C++ and in different ways. This article explains the different ways in which a C++ function can return a vector. In order to code a vector in C++, the vector library has to be included in the program.


1 Answers

You declare a function to return by r-value reference - this should almost never be done (if you return the local object by reference, you will end up with a dangling reference). Instead declare the function to return by value. This way the caller's value will be move constructed by the r-value returned by the function. The returned value will also bind to any reference.

Secondly, no, you should not return using an explicit std::move as this will prevent the compiler to use RVO. There's no need as the compiler will automatically convert any l-value reference returned to an r-value reference if possible.

std::vector<A> func() {     std::vector<A> v;     /* fill v */     return v; // 'v' is converted to r-value and return value is move constructed. } 

More info:

  • Using std::move() when returning a value from a function to avoid to copy
  • Is there any case where a return of a RValue Reference (&&) is useful?
like image 119
Felix Glas Avatar answered Oct 22 '22 14:10

Felix Glas