#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没有被销毁,是何缘故?
因为一个分配在栈中,一个分析在堆中引起?
赐教!