在以下代码中如何可能使用私有析构函数删除对象?我将真正的程序减少到以下示例,但它仍然编译和工作.
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标准说,在这种情况下你会得到不明确的行为(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
:
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; }