问题描述
我在想:他们说如果你手动调用析构函数 - 你做错了。但是总是这样吗?有任何反驳吗?
调用方法时,必须手动调用它,在哪里难以避免?如果使用 operator new()
的重载形式构造对象,则需要手动执行析构函数,除非使用 std :: nothrow
overloads:
T * t0 = new(std :: nothrow)T
delete t0; // OK:std :: nothrow overload
void * buffer = malloc(sizeof(T));
T * t1 = new(buffer)T();
t1->〜T(); // required:delete t1 will be wrong
free(buffer);然而,在显式地调用析构函数的一个相当低的级别上管理内存之外,是 坏设计的标志。也许,它实际上不仅仅是坏的设计,而是彻头彻尾的错误(是的,使用显式析构函数,然后在分配操作符中的复制构造函数调用是一个坏的设计,可能是错误的)。
使用C ++ 2011还有另一个原因要使用显式析构函数调用:当使用广义联合时,需要显式地销毁当前对象并使用placement new创建一个新对象所表示对象的类型。此外,当联合被破坏时,如果需要破坏当前对象,必须显式调用它的析构函数。
I was thinking: they say if you're calling destructor manually - you're doing something wrong. But is it always the case? Are there any counterarguments? Situations, where it is neccessary to call it manually, where it is hard/impossible/impractical to avoid it?
解决方案 Calling the destructor manually is required if the object was constructed using an overloaded form of operator new()
, except when using the "std::nothrow
" overloads:
T* t0 = new(std::nothrow) T();
delete t0; // OK: std::nothrow overload
void* buffer = malloc(sizeof(T));
T* t1 = new(buffer) T();
t1->~T(); // required: delete t1 would be wrong
free(buffer);
Outside managing memory on a rather low level as above calling destructors explicitly, however, is a sign of bad design. Probably, it is actually not just bad design but outright wrong (yes, using an explicit destructor followed by a copy constructor call in the assignment operator is a bad design and likely to be wrong).
With C++ 2011 there is another reason to use explicit destructor calls: When using generalized unions, it is necessary to explicitly destroy the current object and create a new object using placement new when changing the type of the represented object. Also, when the union is destroyed, it is necessary to explicitly call the destructor of the current object if it requires destruction.
这篇关于调用析构函数手动总是坏设计的标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!