空的析构函数vs文字析构函数

Vin*_*ent 16 c++ destructor user-defined-literals constexpr c++11

请考虑以下代码:

#include <iostream>

class Test
{
    public:
        constexpr Test(const int x) : _x(x) {}
        constexpr int get() const {return _x;}
        ~Test() {} // HERE
    protected:
        const int _x;
};

int main()
{
    static constexpr Test test(5);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我删除该行HERE代码编译得很好,但是如果我定义一个空的析构函数,则会导致编译错误,说明Test它是非文字的.

为什么空的析构函数和没有析构函数之间有什么区别呢?

编辑:另一个相关的问题:如果空和文字析构函数不同如何定义受保护的文字析构函数?

For*_*veR 20

引自n3376

7.1.5/9

对象声明中使用的constexpr说明符将对象声明为const.这样的对象应具有文字类型并应初始化.如果它是由构造函数调用初始化的,那么该调用应该是一个常量表达式

3.9/10

在以下情况下,类型是文字类型:

它有一个简单的析构函数......

12.4/5

如果不是用户提供的析构函数是微不足道的,如果:

- 析构函数不是虚拟的,

- 该类的所有直接基类都有微不足道的析构函数

- 对于类类的所有非静态数据成员(或其数组),每个这样的类都有一个简单的析构函数.

否则,析构函数是非平凡的.

clang诊断确实更有用:

error: constexpr variable cannot have non-literal type 'const C'

'C' is not literal because it has a user-provided destructor
Run Code Online (Sandbox Code Playgroud)

  • Clang:1254,其他人:32 (2认同)