据我了解(至少对于c++14
),析构函数不能是constexpr
如果它不是微不足道的(隐式生成或=default
)。声明的意义何在constexpr
具有非平凡析构函数的结构的构造函数?
struct X {
int a_;
constexpr X(int a) : a_{a} {}
// constexpr ~X(){}; // Error dtor cannot be marked constexpr
// ~X(){}; // causes error at y declaration: temporary of non-literal type ‘X’
// in a constant expression .
};
template <int N> struct Y {};
int main() {
Y<X{3}.a_> y; // OK only if the destructor is trivial
(void)y;
}
// tested with c++14 g++-5.1.0 and clang++ 3.5.0
例如std::unique_ptr
有一些构造函数 http://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr constexpr
(默认和nullptr_t
),即使析构函数显然是明确定义的(当然,如果对象是nullptr
,但这是否意味着它仍然有一个显式定义的析构函数来检查对象是否处于空状态,正如我所见,即使是空析构函数也不允许在编译常量表达式)
另一个例子是提案标准::变体 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4542.pdf:它几乎拥有所有的构造函数constexpr
尽管析构函数有签名~variant()
它必须call get<T_j> *this).T_j::~T_j() with j being index().
我缺少什么?
constexpr
构造函数可用于常量初始化,作为静态初始化的一种形式,保证在任何动态初始化发生之前发生。
例如,给定一个全局std::mutex
:
std::mutex mutex;
在一致的实现中(阅读:不是 MSVC),其他对象的构造函数可以安全地锁定和解锁mutex
, 因为std::mutex
的构造函数是constexpr
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)