Does initializing a class with braces guarantee that all member gets default initialized?

2

In the following example, does initializing a Vec3 with braces guarantee that all of x, y, and z get default initialized (func_a()), in difference to func_b() where all members gets undefined values?

struct Vec2 { float x, y; };
struct Vec3 { Vec2 xy; float z; };
auto func_a() {
    Vec3 v{};
    return v;
}
auto func_b() {
    Vec3 v;
    return v;
}

If so, is there any exception where a member does not get initialized even if the class it belongs to get initialized with braces?

Clang and GCC yields different assembly for func_b().

In Clang the assembly is a single ret statement.

In GCC the assembly is similar to func_a():

mov     DWORD PTR [rsp-24], 0x00000000
mov     DWORD PTR [rsp-20], 0x00000000
pxor    xmm1, xmm1
movq    xmm0, QWORD PTR [rsp-24]
ret

(Compiler explorer link https://godbolt.org/z/XqwgSV)

c++11
initialization
undefined
brace-initialization
asked on Stack Overflow Sep 4, 2018 by Viktor Sehr • edited Sep 13, 2018 by Viktor Sehr

1 Answer

1

What corresponds to your example from the reference

T object {}; // (4) (since C++11)

Value initialization is performed in these situations:
...
4) when a named variable (automatic, static, or thread-local) is declared with the initializer consisting of a pair of braces.

The effects of value initialization are:
...
2) if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;

So in your case, zero initialization will take place.

If T is an non-union class type, all base classes and non-static data members are zero-initialized, and all padding is initialized to zero bits. The constructors, if any, are ignored.

answered on Stack Overflow Sep 4, 2018 by P.W • edited Sep 4, 2018 by P.W

User contributions licensed under CC BY-SA 3.0