关于C++中STL的vector容器的析构问题
代码:#include<iostream>#include<string>#include<vector>usingnamespacestd;classTest{publ...
代码:
#include <iostream>#include <string>#include <vector>using namespace std;
class Test{public: int a; Test(int _a): a(_a) {} Test(const Test &obj) {a = (obj.a)+1;} ~Test() {cout << "Destruction:"<<a<<endl;}};
int main(){ Test *a = new Test(23); Test *b = new Test(34); vector<Test> vec; vec.push_back(*a); vec.push_back(*b); delete a; delete b; return 0;}
运行结果说明:a所指的对象在放入vector时被复制了两次,而b所指的对象只复制了一次,这是怎么回事? 展开
#include <iostream>#include <string>#include <vector>using namespace std;
class Test{public: int a; Test(int _a): a(_a) {} Test(const Test &obj) {a = (obj.a)+1;} ~Test() {cout << "Destruction:"<<a<<endl;}};
int main(){ Test *a = new Test(23); Test *b = new Test(34); vector<Test> vec; vec.push_back(*a); vec.push_back(*b); delete a; delete b; return 0;}
运行结果说明:a所指的对象在放入vector时被复制了两次,而b所指的对象只复制了一次,这是怎么回事? 展开
2个回答
展开全部
多加一些打印 看得更清楚一些
#include <iostream>
#include <string>
#include <vector>
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:"<<a<<endl;}
};
int main()
{
Test *a = new Test(23);
Test *b = new Test(34);
vector<Test> vec;
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
#include <iostream>
#include <string>
#include <vector>
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:"<<a<<endl;}
};
int main()
{
Test *a = new Test(23);
Test *b = new Test(34);
vector<Test> vec;
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
光点科技
2023-08-15 广告
2023-08-15 广告
通常情况下,我们会按照结构模型把系统产生的数据分为三种类型:结构化数据、半结构化数据和非结构化数据。结构化数据,即行数据,是存储在数据库里,可以用二维表结构来逻辑表达实现的数据。最常见的就是数字数据和文本数据,它们可以某种标准格式存在于文件...
点击进入详情页
本回答由光点科技提供
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询