#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
class items{
char * name;
public:
items(const char * str){
int len = strlen(str);
this->name = new char [len];
strcpy(this->name,str);
cout << "Default ctor " << this->name << " \[email protected]" << (this) << endl;
}
items(const items& obj){
int len = strlen(obj.name);
this->name = new char [len];
strcpy(name,obj.name);
cout << "Copy ctor " << this->name << " \[email protected]" << this << endl;
}
~items(){
cout << "dtor \t" << this->name << "\[email protected]" << this << endl;
delete [] name;
}
const char * getName() const{
return this->name;
}
};
ostream& operator<<(ostream& stream, const items& obj){
stream << obj.getName();
return stream;
}
int main(int argc, char ** argv){
items Ruler("Ruler"), Pencil("Pencil"), Book("Book"), Notebook("Notebook"), Sharpener("Sharpener");
vector<items> school;
school.push_back(Ruler);
school.push_back(Pencil);
school.push_back(Book);
return 0;
}
我有奇怪的結果。你能解釋一下現場發生的事情嗎? 結果:太多複製ctors我無法弄清楚
Default ctor Ruler @0x62ff1c
Default ctor Pencil @0x62ff18
Default ctor Book @0x62ff14
Default ctor Notebook @0x62ff10
Default ctor Sharpener @0x62ff0c
Copy ctor Ruler @0x9cd1d0
Copy ctor Pencil @0x9cd504
Copy ctor Ruler @0x9cd500
dtor Ruler @0x9cd1d0
Copy ctor Book @0x9c0510
Copy ctor Ruler @0x9c0508
Copy ctor Pencil @0x9c050c
dtor Ruler @0x9cd500
dtor Pencil @0x9cd504
dtor Ruler @0x9c0508
dtor Pencil @0x9c050c
dtor Book @0x9c0510
dtor Sharpener @0x62ff0c
dtor Notebook @0x62ff10
dtor Book @0x62ff14
dtor Pencil @0x62ff18
dtor Ruler @0x62ff1c
默認構造後發生了什麼?爲什麼這個統治者創造太多副本並摧毀他們?這裏有什麼問題?
你的「默認構造函數」根本不是默認的構造函數,這很容易讓人誤解。 – Quentin
如果你解釋一下你期望的副本,我們會更好地解釋你的誤解。 – user2357112
當你推動你的項目上的矢量臨時副本製作 – FamZ