异常时对对象的清理,在栈中和堆中不一样么?

firecityplans 2013-06-23 12:58:24
#include <iostream>

using namespace std;

class Trace {
static int counter;
int objid;

public:
Trace() {
objid= counter++;
cout << "constructing Trace #" << objid << endl;
if( objid == 3 ) throw 3;
}

~Trace() {
cout << "destructing Trace #" << objid << endl;
}
};

int Trace:: counter = 0;

int main() {
try{
Trace n1 ;

Trace array[5];

/*Trace *n1 = new Trace;

Trace *array = new Trace[5];*/

Trace n2; // won't get here
}
catch( int i){
cout << " caught" << i << endl;
}
}

打印日志如下
constructing Trace #0
constructing Trace #1
constructing Trace #2
constructing Trace #3
destructing Trace #2
destructing Trace #1
destructing Trace #0
caught3
请按任意键继续. . .

此方式下n1对象可以被销毁,而如下
class Trace {
static int counter;
int objid;

public:
Trace() {
objid= counter++;
cout << "constructing Trace #" << objid << endl;
if( objid == 3 ) throw 3;
}

~Trace() {
cout << "destructing Trace #" << objid << endl;
}
};

int Trace:: counter = 0;

int main() {
try{

Trace *n1 = new Trace;

Trace *array = new Trace[5];

Trace n2; // won't get here
}
catch( int i){
cout << " caught" << i << endl;
}
}


打印的日志如下:
constructing Trace #0
constructing Trace #1
constructing Trace #2
constructing Trace #3
destructing Trace #2
destructing Trace #1
caught3

即n1没有被销毁,是何缘故?
因为一个分配在栈中,一个分析在堆中引起?

赐教!
...全文
141 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
zybjtu 2013-06-23
  • 打赏
  • 举报
回复
一个new对应一个delete。谁new谁delete
firecityplans 2013-06-23
  • 打赏
  • 举报
回复
引用 5 楼 mougaidong 的回复:
原因就是楼主自己讲的。 很简单:new出来的对象是要自己delete的
明白 了,自己一时犯糊涂了。。。。。。。
turing-complete 2013-06-23
  • 打赏
  • 举报
回复
原因就是楼主自己讲的。 很简单:new出来的对象是要自己delete的
ri_aje 2013-06-23
  • 打赏
  • 举报
回复
我说的管与不管说的是是否调用已构造对象的析构函数。
ri_aje 2013-06-23
  • 打赏
  • 举报
回复
引用 2 楼 firecityplans 的回复:
[quote=引用 1 楼 ri_aje 的回复:] 只负责栈上的对象,堆上的不管。
什么意思?可以解释清楚点么?[/quote] 就是说即便你 catch 了异常,标准也只保证这个管 Trace n1; 但这个不保证管,绝大部分实现都不管 Trace *n1 = new Trace;
firecityplans 2013-06-23
  • 打赏
  • 举报
回复
引用 1 楼 ri_aje 的回复:
只负责栈上的对象,堆上的不管。
什么意思?可以解释清楚点么?
ri_aje 2013-06-23
  • 打赏
  • 举报
回复
只负责栈上的对象,堆上的不管。

64,665

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧