简体   繁体   中英

Why `default` ctor zero-initializes class members?

Given two classes with different constructors:

#include <iostream>

struct A {
    int x;

    A() {};
};

struct B {
    int x;

    B() = default;
};

int main() {
    int x = 5;
    x = 7;

    printf("before: %d\n", x);

    new(&x) A();
    printf("%d\n", x);

    new(&x) B();
    printf("%d\n", x);
}

Output is:

before: 7
7
0

Why default ctor zero-initializes int x ?

You usedvalue initialization ( new A(); ) which is different from default initialization ( new A; ). Notice the parenthesis.

For value initialization :

if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;

And :

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;

And, on the definition of "user-provided" :

A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration.

A has a user provided constructor so it falls in the first case. The just calls its constructor which initializes nothing.

B 's constructor is explicitly defaulted so it isn't user provided, and it is also not deleted, so it falls into the second case. It is zero-initialized then default initializated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM