C ++隐式默认构造函数的意义是什么? [英] What is the point of a C++ implicit default constructor?

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

问题描述

隐式默认构造函数具有一个空的主体和一个空的初始化程序列表(未定义原始类型,并且为用户定义的类型调用了默认构造函数。)



a href = https://stackoverflow.com/a/4982720/572332%20post> post 说

  MyClass * c = new MyClass(); 

确实可以进行成员值初始化,但是调用默认构造函数的意义是什么

  MyClass c时; 



是隐式默认构造函数调用,以确保调用了用户定义类型的默认构造函数(可能具有非平凡的默认构造函数)?






更新



似乎在调用编译器生成的隐式默认构造函数之后,可能无法一致地实例化该对象,即未定义原始类型,并且用户定义的类型可能处于(或可能不处于)已知状态,具体取决于程序员是否提供了默认构造函数。 / p>

为什么编译器会生成一个隐式默认构造函数,该构造函数在被调用时可能会实例化处于未知状态的对象?

解决方案

隐式默认构造函数的点与任何其他构造函数的点都是相同的点。



某些东西需要构造的每个实例给定的班级。类实例本身不会凭空出现的。



如果未声明显式构造函数,则会自动定义隐式默认构造函数,该默认构造函数将构造类的超类。 ,以及任何类成员。



如果类成员是没有显式构造函数的原始类型,则 default-constructs还包括不执行任何操作选项。因此,最后,隐式默认构造函数可能最终什么都不做。但是,如果未指定显式构造函数(当然也没有显式删除隐式默认构造函数),它仍然是定义的。


A implicit default constructor has an empty body and an empty initializer list (primitive types undefined, and the default constructor is called for user defined types).

This post says

MyClass *c = new MyClass();

does indeed do a member-wise value-initialization, but what is the point of calling the default constructor when doing

MyClass c;

?

Is the implicit default constructor called, to ensure that the default constructors for user defined types (which might have non-trivial default constructors) are called?


Update

Seems that after the compiler-generated implicit default constructor is called, the object might not be consistently instantiated, i.e. primitive types undefined, and user defined types might (or might not be) in a known state depending on if the programmer provided default constructors.

Why then does the compiler generate an implicit default constructor which when called might instantiate an object in an unknown state?

解决方案

The point of the implicit default constructor is the same point as of any other constructor.

Something needs to construct every instance of a given class. The class instance is not going to appear out of thin air, by itself. Something, somewhere, has the job of constructing the object.

If an explicit constructor is not declared, an implicit default constructor gets automatically defined, that default-constructs the class's superclasses, and any class members.

Here, "default-constructs" also includes the "do nothing" option, if the class member is a primitive type with no explicit constructor. So, in the end, the implicit default constructor may end up doing nothing. But it is still defined, if an explicit constructor is not specified (and if the implicit default constructor is not explicitly deleted, of course).

这篇关于C ++隐式默认构造函数的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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