#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(){
//cout<<"delete dog "<<name<<endl;
}
};
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;
}
Hello, I'm new to cpp. I tried to use copy constructor in my class dog. I pushed three dogs into the vector, using push_back three times. So I expected copy constructor to be called three times. However, after executing the code, I found that copy constructor was 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'm quite confused about why the dog is copied so many times. I only excute push_back for three times. Thank you.
Thank you for pointing out a similar question: why the copy-constructor is called twice when doing a vector.push_back
In this post, the author only push_back one object, but copy constructor got called twice. However, In my case, when I call push_back once, copy constructor got called only once. I have understood where my problem is, thank you all for your help.