多加一些打印 看得更清楚一些
#include
#include
#include
using namespace std;
class Test
{
public:
int a;
Test(int _a): a(_a) {cout << "default " << a << endl;}
Test(const Test &obj) {a = (obj.a)+1; cout << "copy " << a << endl;}
~Test() {cout << "Destruction:"<};
int main()
{
Test *a = new Test(23);
Test *b = new Test(34);
vector
cout << "push a\n";
vec.push_back(*a);
cout << "push b\n";
vec.push_back(*b);
cout << "delete a\n";
delete a;
cout << "delete b\n";
delete b;
cout << "end\n";
return 0;
}
运行结果&解释
default 23
default 34
//初始化a b
push a
copy 24
//push a并复制出来24
push b
copy 25
copy 35
Destruction:24
//这里,由于vector空间不足,新申请空间,并把现有的24复制过去(变成了25),再压入新的34(变成35)
//同时原本的24被析构
delete a
Destruction:23
//删除a 析构23
delete b
Destruction:34
//删除b 析构34
end
Destruction:25
Destruction:35
//程序退出 删除容器中的25 35
内存分配啊 VECTOR是动态数组啊
如果长度不够的时候 就会new 一个新的数组出来然后copy第二次复制就这么来的