gpt4 book ai didi

c++ - 理解隐式声明的默认构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:19:07 25 4
gpt4 key购买 nike

我试图了解编译器的默认构造函数是如何工作的。我做了这个例子:

#include <iostream>

class Base {
public:
int number;
};

class Test1 : public Base {
};

class Test2 {
public:
Base base;
};

int main() {
Test1 test1;
Test2 test2;
std::cout<<test1.number<<std::endl;
std::cout<<test2.base.number<<std::endl;
}

这个测试程序的输出是,对于test1 0,对于test2 是一个未初始化的(随机)数。现在我的问题是:为什么在第一种情况下 (test1) 编译器的默认构造函数将 number 初始化为 0 而对于 test2 不是吗?

编辑:根据答案,两者都会产生未定义的行为。那么,在这个程序中,编译器的默认构造函数做了什么?

最佳答案

根据 8.5/12,未初始化对象的值不确定:

If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17).

不幸的是,根据 §8.5/7,int 属于“非默认初始化类型”的类别:

To default-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type (Clause 9), the default constructor (12.1) for T is called (and the initialization is ill-formed if T has no default constructor or overload resolution (13.3) results in an ambiguity or in a function that is deleted or inaccessible from the context of the initialization);
  • if T is an array type, each element is default-initialized;
  • otherwise, no initialization is performed.

关于c++ - 理解隐式声明的默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22795037/

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