Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector as class member

Tags:

c++

c++11

class A
{
   private:
      std::vector<int>myvec;
   public:
      const std::vector<int> & getVec() const {return myvec;}
};
void main()
{
   A a;
   bool flag = getFlagVal();
   std::vector<int> myVec;
   if(flag)
      myVec = a.getVec(); 
   func1(myVec);
}

In the line myVec= a.getVec(), there is a copy of vector although it is returned by reference. If flag is not true, an empty vector will be passed.

Anyway to avoid this copy ?

like image 393
Anirban Saha Avatar asked Apr 28 '26 10:04

Anirban Saha


1 Answers

func1(flag ? a.getVec() : std::vector<int>());

is one way.

This will work if func1 takes the vector by const reference, since both anonymous temporaries can bind to it.

like image 59
Bathsheba Avatar answered May 01 '26 01:05

Bathsheba