假设我有类似的东西:
class obj001
{
public:
obj001() {
std::cout << "ctor == obj001" << std::endl;
}
~obj001() {
std::cout << "dtor == obj001" << std::endl;
}
};
class obj002
{
public:
obj002() {
std::cout << "ctor == obj002" << std::endl;
}
~obj002() {
std::cout << "dtor == obj002" << std::endl;
}
};
class packet001
{
public:
packet001(): p01(NULL), p02(NULL) {
/*p01 = new obj001;
p02 = new obj002;
throw "hahaha";*/
std::cout << "CTOR == PACKET01" << std::endl;
}
~packet001() {
delete p01;
delete p02;
std::cout << "DTOR == PACKET01" << std::endl;
}
void init() {
p01 = new obj001;
p02 = new obj002;
throw "hahaha";
}
obj001* p01;
obj002* p02;
};
如果我这样做:
try
{
packet001 superpack;
superpack.init();
}
catch(char* type)
{
}
然后init()
失败了,Dtorsuperpack
就会被调用。
但是如果我把内存分配放在 的 Ctor 里面superpack
,
(当然不要执行init()
)
那么在 Ctor 失败后,Dtor 就不会被调用,所以p01
会p02
被泄露。
那么,最好使用类似的东西init()
?
谢谢!