Member not zeroed, a clang++ bug?

前端 未结 4 1364
孤街浪徒
孤街浪徒 2020-12-15 08:36

Consider the following code:

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

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

int main() {
    B* p = new B {};
    std:         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 09:06

    Clang is correct, per the C++11 standard plus relevant DRs

    In the original C++11 specification, B{} would perform value-initialization, resulting in a.i being zero-initialized. This was a change in behavior compared to C++98 for cases like

    B b = {};
    

    ... which were handled as aggregate initialization in C++98 but treated as value-initialization in C++11 FDIS.

    However, the behavior in this case was changed by core issue 1301, which restored the C++98 behavior by mandating that aggregate initialization is used whenever an aggregate is initialized by a braced-init-list. Since this issue is considered a DR, it is treated as de facto applying to earlier revisions of the C++ standard, so a conforming C++11 compiler would be expected to perform aggregate initialization here rather than value-initialization.

    Ultimately, it's a bad idea to rely on value-initialization to initialize your data members, especially for a class that has user-provided constructors.

提交回复
热议问题