【问题标题】:`is_trivially_destructible` does not work with inherited class`is_trivially_destructible` 不适用于继承的类
【发布时间】:2017-01-24 12:11:10
【问题描述】:
#include <iostream>
using namespace std;


    class NoConstructOperation
    {
    protected:
        NoConstructOperation() = default;
        virtual ~NoConstructOperation() = default;
    public:
        NoConstructOperation(const NoConstructOperation&) = delete;
        NoConstructOperation& operator =(NoConstructOperation&) = delete;
        NoConstructOperation(NoConstructOperation&&) = delete;
        NoConstructOperation& operator = (NoConstructOperation&&) = delete;
    };

class Myclass:public NoConstructOperation
{

};


int main() {
    static_assert(!std::is_trivially_destructible<Myclass>::value, "Compiler provided destructor is public: Please declare it private");
    return 0;
}  

如果我不使用NoConstructOperation 继承Myclass,上面的代码会使用静态断言给出编译错误。
但是如果我用NoConstructOperation 继承Myclass is_trivially_destructible 检查不起作用,即使Myclass 构造函数是公共的。这段代码可以编译,是什么原因

【问题讨论】:

  • 你想用这个实现什么?

标签: c++ c++11 visual-c++ c++14


【解决方案1】:

您将NoConstructorOperation 的析构函数定义为virtual。删除 virtual 将按预期触发静态断言:wandbox example

来自cplusplus.com

普通可破坏类是一个类(用类、结构或联合定义):

  • 使用隐式定义的析构函数。

  • 析构函数不是虚拟的。

  • 它的基类和非静态数据成员(如果有的话)本身也是可简单破坏的类型。

来自标准草案N4567 $12.4:

如果析构函数不是用户提供的并且满足以下条件,则它是微不足道的:

(5.4) — 析构函数不是虚拟的,

(5.5) — 其类的所有直接基类都有微不足道的析构函数,并且

(5.6) — 对于其类的所有属于类类型(或其数组)的非静态数据成员,每个此类 类有一个微不足道的析构函数。

【讨论】:

  • 将基类析构函数设为非虚拟可能会产生不同的副作用。
  • 这不是唯一的问题
  • 我想强制执行我的客户端类,即 Myclass 应该删除复制/移动构造函数/赋值,并且 ```` 构造函数和析构函数在 private 范围内。任何更好的方法。
  • @gauravbharadwaj 为什么???只需给(基)类一个已删除的副本和已删除的作业。但仅当这些需要时。构造函数(可能)和析构函数(肯定)应该保持公开。
  • @DieterLücking 为什么析构函数应该保持公开(肯定)?如果某些东西要始终由智能指针管理,那么公共析构函数就不是必需的了。
猜你喜欢
  • 2016-06-28
  • 1970-01-01
  • 2020-05-07
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
相关资源
最近更新 更多