gpt4 book ai didi

c++ - 成员未归零,一个 clang++ 错误?

转载 作者:可可西里 更新时间:2023-11-01 18:00:03 26 4
gpt4 key购买 nike

考虑以下代码:

class A {
public:
int i;
A() {}
};

class B {
public:
A a;
int i;
};

int main() {
B* p = new B {};
std::cout << p->i << " " << p->a.i << "\n";
}

在 clang++ 中使用 -std=c++11 编译,p->i 结果为零,但 p->a.i 不是。只要它的类没有用户提供的构造函数,整个对象不应该被清零吗?

编辑:由于评论中有一些广泛的讨论,我认为最好在此处添加一些标准摘录:

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.

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++11 标准和相关 DR,Clang 是正确的

在最初的 C++11 规范中,B{} 将执行值初始化,导致 a.i 被零初始化。对于像

这样的情况,与 C++98 相比,这是一个行为变化
B b = {};

...在 C++98 中作为聚合初始化处理,但在 C++11 FDIS 中作为值初始化处理。

然而,这种情况下的行为被core issue 1301改变了,它通过强制在聚合由 braced-init-list 初始化时使用聚合初始化来恢复 C++98 行为。由于此问题被视为 DR,它被视为适用于 C++ 标准的早期修订版事实上,因此符合 C++11 的编译器应在此处执行聚合初始化而不是值-初始化。

最终,依靠值初始化来初始化数据成员并不是一个好主意,尤其是对于具有用户提供的构造函数的类。

关于c++ - 成员未归零,一个 clang++ 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31640478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com