为什么C ++对象具有默认析构函数? [英] Why to C++ objects have a default destructor?

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

问题描述

例如,当我不声明构造函数时,编译器将为我提供一个默认构造函数,该构造函数将不带参数且没有定义(空主体),因此将不执行任何操作

When I don't declare a constructor for example, the compiler will provide me with a default constructor that will have no arguments and no definition (empty body), and thus, will take no action.

因此,例如,如果我完成了一个对象,默认析构函数是否会重新分配该对象使用的(空闲)内存?如果没有,我们为什么要得到它?

So, if I'm finished with an object for example, wouldn't the default destructor reallocate (free) memory used by the object? If it doesn't, why are we getting it?

而且,也许相同的问题也适用于默认构造函数.如果什么都不做,为什么默认情况下会为我们创建它?

And, maybe the same question applies to the default constructor. If it does nothing, why is it created for us by default?

推荐答案

说编译器生成的默认构造函数不执行任何操作是错误的.它等效于用户定义的构造函数,该构造函数具有空的主体和空的初始化程序列表,但这并不意味着它不执行任何操作.这是它的作用:

It's wrong to say that a compiler-generated default constructor takes no action. It is equivalent to a user-defined constructor with an empty body and an empty initializer list, but that doesn't mean it takes no action. Here is what it does:

  1. 它调用基类的默认构造函数.
  2. 如果类是多态的,它将初始化vtable指针.
  3. 它调用所有拥有它们的成员的默认构造函数.如果有一个成员带有一些构造函数,但没有默认构造函数,则是编译时错误.

并且只有当一个类不是多态的,没有基类并且没有需要构造的成员时,编译器生成的默认构造函数才会执行任何操作.但是即使那样,出于其他答案中所述的原因,有时有时仍需要默认构造函数.

And only if a class is not polymorphic, has no base class and has no members that require construction, then a compiler-generated default constructor does nothing. But even then a default constructor is sometimes necessary for the reasons explained in other answers.

析构函数也是如此-它调用基类的析构函数以及所有拥有它们的成员的析构函数,因此在一般情况下,编译器生成的析构函数不执行任何操作都是不正确的.

The same goes for the destructor - it calls base class'es destructor and destructors of all members which have them, so it isn't true in general case that a compiler-generated destructor does nothing.

但是内存分配确实与此无关.内存是在调用构造函数之前分配的,只有在最后一个析构函数完成之后才释放内存.

But memory allocation really has nothing to do with this. The memory is allocated before the constructor is called, and it is freed only after the last destructor has finished.

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

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