我可以检查初始化列表中设置的构造函数主体中的变量吗?

Can I check variables in a constructor body that were set in the initialization list?

我怀疑在初始化列表的情况下构造函数的主体是如何工作的。如果构造函数传递的值不是允许值,需要抛出异常,那么这样做是否正确?

Foo(int a_) : a(a_) {
  if (a>0)
    throw std::invalid_argument("positive value!");
};

我对如何评估它有疑问,以防情况更复杂。

根据 cppreference,假设初始化列表将在构造函数的 'body' 执行之前完成是绝对安全的(第 4 项的粗体是我的):

The order of member initializers in the list is irrelevant: the actual order of initialization is as follows

  • 1 If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in depth-first left-to-right traversal of the base class declarations (left-to-right refers to the appearance in base-specifier lists)
  • 2 Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list
  • 3 Then, non-static data members are initialized in order of declaration in the class definition.
  • 4 Finally, the body of the constructor is executed

现在,虽然 cppreference 不是实际标准,但在此类问题上通常是准确的。

编辑:draft C++14 (§ 12.6.2) standard(该 PDF 第 283-284 页)确认了 cppreference 的内容。 (是的,我知道 OP 指定 C++11 - 但我无法在线获得该标准的 link,我非常怀疑这件事的标准在11、14 和 17!)