在我的构造函数中,如果其中包含任何代码,我必须销毁所有剩余资源。我想避免编写重复的代码,所以我只在catch块中调用析构函数即可释放已创建的任何资源。这样安全吗?
我知道如果构造函数抛出异常,则不会调用析构函数,因此我尝试在msvc中编译一些代码,但似乎没有什么错,但是我不确定这是否很幸运。
Object::Object(){
try{
// Initialize multiple resources here.
}catch(...){
this->~Object(); // Is this safe?
throw;
}
}
Object::~Object(){
// release multiple resources, if initialized.
}
Run Code Online (Sandbox Code Playgroud) c++ constructor try-catch object-lifetime explicit-destructor-call