考虑以下代码:
#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/