Anirban Saha
Anirban Saha

Reputation: 149

Vector as class member

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 ?

Upvotes: 3

Views: 81

Answers (1)

Bathsheba
Bathsheba

Reputation: 234635

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.

Upvotes: 8

Related Questions