【问题标题】:How to destruct a singleton instance, or why the follow code works for destructor?如何破坏单例实例,或者为什么下面的代码适用于析构函数?
【发布时间】:2019-10-10 08:35:46
【问题描述】:

以下代码用于删除单例实例,为什么需要删除前的工作?

// @brief Destruct the singleton instance
// @note Only work with gcc/clang
__attribute__((destructor)) static void delete_() {
    //works before delete
    typedef char T_must_be_complete[sizeof(T) == 0 ? -1 : 1];
    (void) sizeof(T_must_be_complete);
    delete instance_;
}

【问题讨论】:

  • 而 T 是模板类型名 template,并且 instance_ = new T()

标签: c++ design-patterns parallel-processing


【解决方案1】:

这是一个删除,首先检查类型是否完整。类似于boost::checked_delete

它的想法是在尝试删除 incomplete type (which has a good chance of causing undefined behavior, depending on the type) 时生成编译错误。

例如(为方便起见,使用boost::checked_delete,因为我不知道您的delete_ 所属的类的细节,但它们基本相同):

struct X;

void foo(X* x) {
    boost::checked_delete(x);
}

请注意,常规的 delete x; 可能会导致编译器发出警告(取决于您的编译器),但这不能保证。

【讨论】:

  • 我想知道为什么一个简单的 (void)sizeof(T); 没有删减它 - 是否有 GCC 或 Clang 版本会为不完整的类型返回 0
  • @Quentin :我不能代表 OP 的代码,但对于非常相似的 boost::checked_delete,增加了复杂性以覆盖 CodeWarrior 8 错误:commitmailing list
  • 哦,还有 Intel 7 编译器:commit, mailing list
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-07
  • 2015-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多