gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:35:17 25 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.

每个项目的第二个项目符号在这里适用。

最佳答案

Clang 是正确的,符合 C++11 标准以及相关的 DR

在最初的 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/21932544/

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