加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:53:36 所属栏目:百科 来源:网络整理
导读:在以下代码中如何可能使用私有析构函数删除对象?我将真正的程序减少到以下示例,但它仍然编译和工作. 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?
在以下代码中如何可能使用私有析构函数删除对象?我将真正的程序减少到以下示例,但它仍然编译和工作.
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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读