c++ - 空析构函数与文字析构函数

标签 c++ c++11 destructor constexpr user-defined-literals

考虑以下代码:

#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;
}

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

为什么空析构函数和没有析构函数有什么区别?

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

最佳答案

引自 n3376

7.1.5/9

A constexpr specifier used in an object declaration declares the object as const. Such an object shall have literal type and shall be initialized. If it is initialized by a constructor call, that call shall be a constant expression

3.9/10

A type is a literal type if:

it has a trivial destructor...

12.4/5

A destructor is trivial if it is not user-provided and if:

— the destructor is not virtual,

— all of the direct base classes of its class have trivial destructors, and

— for all of the non-static data members of its class that are of class type (or array thereof), each such class has a trivial destructor.

Otherwise, the destructor is non-trivial.

clang 诊断确实提供更多信息:

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

'C' is not literal because it has a user-provided destructor

关于c++ - 空析构函数与文字析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14255541/

相关文章:

c++ - 服务器不会连接到多个客户端?

c++ - 如何有条件地将元素添加到 std::array - C++11

c++ - 如何将static_cast转换为变量类型

c++ - 这两种在 C++ 中实现函数的方法有什么区别?

c++ - 在线程内使用全局数组

c++ - 有没有一种安全的方法可以同时使用 C++11 智能指针和原始指针接口(interface)?

c++ - 模糊指向堆或堆栈对象的智能指针

c++ - 在 Debug模式下销毁 Protocol Buffer 消息比在 Release模式下慢近 500 倍

c++ - 从默认构造函数调用成员的析构函数

c++ - 在析构函数中要破坏什么,不要破坏什么