c++ - C++ 初始值设定项列表中的默认值

标签 c++ standards initializer-list

我昨天才知道,为初始化列表项指定参数是可选的。但是,这种情况发生的规则是什么?

在下面的例子中,ptr 是否会被初始化为 0,切换为 false,Bar 默认构造?我想这个问题有点多余,因为如果未指定的参数值 == 未定义的行为,初始化列表中将没有什么意义。

我是否也可以指出 C++ 标准的部分,该部分说明了在初始化列表项没有被赋予参数的情况下的行为?

class Bar
{
    Bar() { }
};

class SomeClass;
class AnotherClass
{
public:
    SomeClass *ptr;
    bool toggle;
    Bar bar;

    AnotherClass() : ptr(), toggle(), bar() { }
    // as opposed to...
    // AnotherClass() : ptr(NULL), toggle(false), bar(Bar()) { }
};

最佳答案

是的,成员将分别初始化为零和默认构造的对象。

C++ 11 标准在 12.6.2/7 中指定了这种行为:

The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of 8.5 for direct-initialization.

8.5/10 依次为:

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

第 8.5/7 段定义值初始化:

To value-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized.

最后,8.5/5 定义了零初始化:

To zero-initialize an object or reference of type T means:

  • if T is a scalar type (3.9), the object is set to the value 0 (zero), taken as an integral constant expression, converted to T;
  • if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;
  • if T is a (possibly cv-qualified) union type, the object’s first non-static named data member is zero- initialized and padding is initialized to zero bits;
  • if T is an array type, each element is zero-initialized;
  • if T is a reference type, no initialization is performed.

关于c++ - C++ 初始值设定项列表中的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14259602/

相关文章:

c - 一元运算符 : implementation defined or undefined

c++ - QTreeWidget 中的垂直行间距

html - 浏览器从标准输入读取 HTML

architecture - 数据交换标准

c++ - 使用额外检查初始化 const 变量

c++ - 在编译时验证 std::initializer_list 的内容

c++ - 媒体基础音频/视频捕获到 MPEG4 FileSink 产生不正确的持续时间

c++ - 在 std::remove_if 执行期间遍历容器是否安全?

c++ - 是否有 "nice"方法来处理来自多个源的重组多播?

c++ - 为什么存在 C++11 std::initializer_list 构造函数重载规则?