C ++默认析构函数 [英] C++ default destructor

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

问题描述

例如,当我不声明一个构造函数时,编译器将为我提供一个默认构造函数将没有参数和定义(body),因此将采取无操作

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 (body), and thus, will take no action.

如果我现在不声明一个 destructor ,编译器将为我提供一个没有定义(body)的默认析构函数,因此,我认为

If I now don't declare a destructor, the compiler will provide me with a default destructor with no defintion (body), and thus, I think 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 doesn 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. 它调用具有它们的所有成员的默认构造函数。如果有一个成员有一些构造函数,但没有默认的,那么它是一个编译时错误。

类没有多态性,没有基类,没有需要构造的成员,那么编译器生成的默认构造函数什么都不做。但是即使这样一个默认的构造函数有时是必要的,因为在其他答案解释的原因。

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天全站免登陆