为什么要为具有非平凡析构函数的类声明constrexpr构造函数(例如unique_ptr,std :: variant)

博洛夫

据我了解(至少对于而言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().

我想念什么?

TC

constexpr 构造函数可用于常量初始化,这是静态初始化的一种形式,可以保证在任何动态初始化发生之前进行。

例如,给定一个全局变量std::mutex

std::mutex mutex;

在一致的实现中(阅读:不是MSVC),其他对象的构造函数可以安全地锁定和解锁mutex,因为std::mutex的构造函数是constexpr

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章