Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

c++11

I read a couple of posts on how to return a vector from a method include these ones:

  1. c11 rvalues and move semantics confusion return statement

  2. want speed pass by value

  3. why does visual studio not perform return value optimization rvo

  4. 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?

like image 903
CrSe Avatar asked Feb 27 '15 08:02

CrSe


1 Answers

//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

like image 162
KillianDS Avatar answered Sep 18 '22 21:09

KillianDS