#include<iostream>
#include<vector>
#include<list>
#include<queue>
#include<map>
using namespace std;
class dog{
public:
string name;
dog();
dog(const dog & d);
void barkname(){
cout<<"bark "<<name<<endl;
}
virtual ~dog(){
}
};
dog::dog(){
cout<<"blank dog"<<endl;
this->name="blank";
}
dog::dog(const dog &d){
cout<<"copy dog"<< " "+d.name<<endl;
string temp=d.name;
this->name=temp+" copied";
}
int main(){
dog d;
d.name="d";
dog dd;
dd.name="dd";
dog ddd;
ddd.name="ddd";
vector<dog> doglist;
doglist.push_back(d);
doglist.push_back(dd);
doglist.push_back(ddd);
return 0;
}
Hi, I am new to cpp. I tried using the copy constructor in my cool dog. I injected three dogs into a vector using push_back three times. Therefore, I expected the copy constructor to be called three times. However, after executing the code, I found that the copy constructor is called six times with the following results:
blank dog
blank dog
blank dog
copy dog d
copy dog dd
copy dog d copied
copy dog ddd
copy dog d copied copied
copy dog dd copied
I am very confused about why the dog is copied so many times. I only ask push_back three times. Thank.
Thank you for pointing out a similar question:
why copy-constructor is called twice when vector.push_back is executed
push_back , . , , push_back , . , , .