简体   繁体   English

为什么`default` ctor 对类成员进行零初始化?

[英]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 ?为什么default ctor 零初始化int x

You usedvalue initialization ( new A(); ) which is different from default initialization ( new A; ).您使用了与默认初始化new A; )不同的值初始化new A(); 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;如果 T 是没有默认构造函数或具有用户提供或删除的默认构造函数的类类型,则该对象是默认初始化的;

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;如果 T 是具有既不是用户提供也不是删除的默认构造函数的类类型(即,它可能是具有隐式定义或默认默认构造函数的类),则对象被零初始化,然后它是默认的-如果它有一个非平凡的默认构造函数,则初始化;

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. A有一个用户提供的构造函数,所以它属于第一种情况。 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. B的构造函数是显式默认的,所以它不是用户提供的,也没有被删除,所以它属于第二种情况。 It is zero-initialized then default initializated.它是 零初始化然后默认初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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