从构造函数初始值设定项中抛出异常

Any*_*orn 4 c++ exception ctor-initializer

从构造函数初始值设定项中抛出异常的最佳方法是什么?

例如:

class C {
  T0 t0; // can be either valid or invalid, but does not throw directly
  T1 t1; // heavy object, do not construct if t0 is invalid,  by throwing before
  C(int n)
    : t0(n), // throw exception if t0(n) is not valid
      t1() {}
};
Run Code Online (Sandbox Code Playgroud)

我想也许制作包装纸,比如说t0(throw_if_invalid(n)).

处理此类案件的做法是什么?

Pot*_*ter 8

可以throw从初始化表达式(多个)t0t1,或者至少需要一个参数的任何构造.

class C {
  T0 t0; // can be either valid or invalid, but does not throw directly
  T1 t1; // heavy object, do not construct if t0 is invalid, by throwing before
  C(int n) // try one of these alternatives:
    : t0( n_valid( n )? n : throw my_exc() ), // sanity pre-check
OR    t1( t0.check()? throw my_exc() : 0 ), // add dummy argument to t1::t1()
OR    t1( t0.check()? throw my_exc() : t1() ) // throw or invoke copy/move ctor
      {}
};
Run Code Online (Sandbox Code Playgroud)

请注意,throw表达式具有void类型,使其throw更像是运算符而不是语句.该?:运营商有一个特殊的情况下,以防止void从它的类型推演干扰.