了解隐式声明的默认构造函数 [英] Understanding implicitly declared default costructor

查看:224
本文介绍了了解隐式声明的默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  #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:


如果没有为对象指定初始化器,则对象将被初始化。当获得具有自动或动态存储持续时间的对象的存储时,对象具有不确定的值,并且如果不对对象执行初始化,则该对象保持不确定的值,直到该值被替换(5.17)。

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


默认初始化类型T的对象意味着:




  • 如果T是(可能是cv限定的)类类型(第9条),则调用T的默认构造函数(12.1)没有默认构造函数或重载解析(13.3)会导致歧义,或者在初始化上下文中被删除或无法访问的函数);

  • 如果T是数组类型,是默认初始化的;

  • 否则不执行初始化。



I'm trying to understand how the compiler's default constructor works. I made this example:

#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;
}

The output of this test program is, for test1 0, and for test2 is a uninitialized (random) number. Now my question is: why in the first case (test1) the compiler's default constructor initialize number to 0 but for test2 it doesn't?

Edit: According to answers both makes undefined behavior. So, in this program, what the compiler's default constructor does?

解决方案

The value of an uninitialized object is indeterminate as per 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).

Unfortunately for you, int falls into the category of "non-default-initialized types" as per §8.5/7:

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.

这篇关于了解隐式声明的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆