is it required by the standard to call non-trivial destructor when you know that in this specific case the destructor is a noop ?
is the code likely to be broken by compliers if the destructor is not called ?
the use case is a class that contain a dynamicly allocated pointer. by default this pointer is obtained by new in the constructor. this class can also get its dynamicly allocated pointer from an allocator. the class keeps track of …
c++ memory-management lifetime language-lawyer explicit-destructor-call
在我的构造函数中,如果其中包含任何代码,我必须销毁所有剩余资源。我想避免编写重复的代码,所以我只在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
虽然我知道这可能不是最好的想法,但我假设:
(即定义行为)手动调用对象的析构函数,然后将内存重用于另一个对象是否合法?
定义:
class A {
int a, b, c;
A() {}
~A() {}
}
A createObject() {
A object;
return object;
}
Run Code Online (Sandbox Code Playgroud)
码:
A* object = new A();
// Use object...
object->~A();
*object = createObject();
Run Code Online (Sandbox Code Playgroud) 可以使用析构函数调用语法显式析构 C++ 对象(对于非类类型伪析构)。但看起来除了普遍接受的语法之外,几乎所有现代编译器都支持自己的调用析构函数的方式:
using T = int;
const int x = 1;
int main() {
x.~T(); //ok everywhere
x.~int(); //#1: ok in MSVC only
x.~auto(); //#2: ok in GCC only
x.~decltype(x)(); //#3: ok in Clang and MSVC only
}
Run Code Online (Sandbox Code Playgroud)
除了x.~T()适用于所有编译器的 ,还有至少 3 个其他选项,演示:https : //gcc.godbolt.org/z/895bd9T5c
根据标准,选项 #1、#2 或 #3 中的任何一个是否合法,或者它们都只是相应编译器的扩展/错误?
析构函数的语法是~classname. 这导致需要在析构函数调用中显式写入对象的类型。为了避免这种情况,C++17 引入了std::destroy_at.
那么,Bjarne Stroustrup 选择~classname析构函数语法的最初理由是什么?如果语法不依赖于类型,std::destroy_at则不需要。