lundi 25 septembre 2017

Deep Copy behaviour of a vector while returning from the function [duplicate]

This question already has an answer here:

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;
}

Aucun commentaire:

Enregistrer un commentaire