How to return a class member vector in c++11

c++, c++11, std

Solution

//1 - classic way?
void GetVect(std::vector<int>& v)
  {
     v = vect;// assignment with swap?
  }

This is just plain ugly, you still need a copy and you make your interface too complex.

//2 - RVO?
std::vector<int> GetVect()
  {
    return vect;
  } 

//3 - RVO with const?
std::vector<int> GetVect() const
  {
    return vect;
  }

Functionally the same, but you likely want 3 to indicate that `getVect` does not change your class state so `const` semantics can be applied correctly.

//4 - just move?
std::vector<int> GetVect() 
  {
    return std::move(vect);
  }  

It seems very unlikely you want this, after calling `GetVect` the internal `vect` will no longer contain any elements.

 //5 - move with {}?
std::vector<int> GetVect() 
  {
    return { std::move(vect) };
  }  

This should end up being the same as 4, you just call the return object's move constructor more explicitly.

For performance what you might actually want is this:

const std::vector<int>& GetVect() const
{
    return vect;
}

This way you can read the object without the need for copying. If you want to write to the returned vector, create a copy explicitly. More details can be found in this question

Problem

I read a couple of posts on how to return a vector from a method include these ones: c11 rvalues and move semantics confusion return statement want speed pass by value why does visual studio not perform return value optimization rvo Wiki - Return Value Optimization and I'm still confused on how to pass a vector the right way in VS2013 and what are the differences between the following methods in this code(the questions are marked in the comments): ``` class Foo{ private: std::vector<int> vect; public: //1 - classic way? void GetVect(std::vector<int>& v) { v = vect;// assignment with swap? } //2 - RVO? std::vector<int> GetVect() { return vect; } //3 - RVO with const? std::vector<int> GetVect() const { return vect; } //4 - just move? std::vector<int> GetVect() { return std::move(vect); } //5 - move with {}? std::vector<int> GetVect() { return { std::move(vect) }; } } ``` So I m not sure if //1 is an explicit form of //2, not sure if 3 works. What are the differences between 4 and 5? How to test it if RVO works for vectors in VS2013?

Original source

Related problems