1

It will be helpful is someone can explain why the vector deep copy doesn't work when i return it from a function

I have a struct with constructor and copy constructor like this

struct  {
   A() { cout<<"Constructor..."<<endl; }
   A(const A &) { cout<<"Copy Constructor...."<<endl;
};

If I write a main program like this

int main() {
   A a1;  // constructor gets called here
   vector<A> vec;
   vec.push_back(a1)  // Copy constructor gets called here

   vector<A> copyvec = vec; // Again copy constructor gets called here
}

However, if I change the code like this

vector<A> retvecFunc() {
    A a1;   // Constructor gets called
    vector<A> vec;
    vec.push_back(a1); // Copy Constructor gets called

    return vec; // copy constructor **DOESN'T GETS CALLED**
}

my main function is written as

int main() {
   vector<A> retVec = retvecFunc();
   return 0;
}
Daksh Gupta
  • 7,554
  • 2
  • 25
  • 36
  • You might want to do some research about [copy-elision and return value optimizations](http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization). – Some programmer dude Sep 25 '17 at 09:35

1 Answers1

3

It's the compiler implementing *Named Return Value Optimisation".

An additional temporary copy of vec is not created.

A compiler is allowed to do this even if there are side effects (such as not printing the console messages in your case).

From C++17, this is compulsory for compilers to implement.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483