据我了解(至少对于而言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
有一些构造函数 constexpr
(default和nullptr_t
),nullptr
但这并不意味着它仍然具有显式定义的析构函数,以便检查是否对象处于空状态,正如我所见,即使是空的析构函数也不允许在编译常数表达式中使用对象)
另一个例子是对std :: variant的建议: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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句