c – 使用私有析构函数删除对象

前端之家收集整理的这篇文章主要介绍了c – 使用私有析构函数删除对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在以下代码中如何可能使用私有析构函数删除对象?我将真正的程序减少到以下示例,但它仍然编译和工作.
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;
}

猜你在找的C&C++相关文章