使用私有析构函数删除对象 [英] Deleting object with private destructor
问题描述
在以下代码中,如何允许使用私有析构函数删除对象?我已经减少了真正的程序到以下示例,但它仍然编译和工作。
How is that possible that it is allowed to delete object with private destructor in the following code? I've reduced real program to the following sample, but it still compiles and works.
class SomeClass;
int main(int argc, char *argv[])
{
SomeClass* boo = 0; // in real program it will be valid pointer
delete boo; // how it can work?
return -1;
}
class SomeClass
{
private:
~SomeClass() {}; // ! private destructor !
};
推荐答案
您正在尝试删除不完整类类型的对象。 C ++ Standard在这种情况下会得到未定义的行为(5.3.5 / 5):
You are trying to delete object of incomplete class type. C++ Standard says that you'll get undefined behavior in this case (5.3.5/5):
如果被删除的对象不完整类类型在删除点和完整的类有一个非平凡的析构函数或释放函数,行为是未定义的。
If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.
要检测此类情况,您可以使用 boost :: checked_delete
:
To detect such cases you could use boost::checked_delete
:
template<typename T>
inline void checked_delete( T* p )
{
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete p;
}
这篇关于使用私有析构函数删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!