如何在C ++中实现构造函数和析构函数? [英] How are constructors and destructors implemented in C++?

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

问题描述

我有2个类Base和Derived(派生自Base)。
当我写 -

  Derived * d1 = new Derived; 
delete d1;

编译器看到d1是一个Derived类型对象。所以它调用派生类构造函数(它调用基类构造函数)。我在这里有两个问题 -



1)为什么我们遵循这个顺序?



构造函数一起工作来分配内存?我需要一些实现细节



现在下一个语句是delete d1。因此编译器看到d1是一个派生类型对象,因此调用派生类的destuctor(在删除派生类成员后调用基类的析构函数)。我在这里有一个问题 -



1)这些析构函数如何一起工作?假设派生类析构函数在内存中传递d1的地址。

(1)这个基类不会释放这个空间。依赖于派生类,但另一种方法是可能的。也就是说类不能知道任何派生类有哪些字段,因此 Base :: Base 不会,也不能碰他们。换句话说, Derived :: Derived 可以访问 Base :: member 。因此,在之前 Base :: Base 初始化 Base :: member 有机会使用 Base :: member`。



(2)构造函数不分配内存。这是 new 的任务。或者如果对象是全局的,编译器的。使用 this 调用构造函数已经指向分配的内存;



在基础和派生构造函数的情况下,一个常见的实现插入对生成的代码中的Base构造函数的调用用于派生构造函数。使用单继承,Base和Derived类通常共享相同的这个指针,因此Derived constrcutor可以传递它获得的同一个指针。



(1)就像构造函数不分配内存一样,析构函数不释放它。这是 delete 的任务 - 再次,对于全局变量,编译器会这样做。


I have 2 classes Base and Derived (derived publically from Base). When I write -

Derived * d1 = new Derived;
delete d1;

Compiler sees that d1 is a Derived type object. So it calls the derived class constructor (which calls the base class constructor). I have 2 questions here -

1) Why do we follow this order?

2) How do these constructors work together to allocate memory? I need some implementation details

Now the next statement is delete d1. So compiler sees that d1 is a derived type object and so calls the destuctor of derived class (which calls the destructor of base class after deleting the derived class members). I have one question here -

1) How do these destructors work together? Lets say the derived class destructor is passed the address of d1 in memory. How do these destructors free up the space now?

解决方案

(1) The base class does not depend on the derived class, but the other way around is possible. I.e. a Base class cannot know which fields any Derived class has, so Base::Base won't and can't touch them. The other way around is possible, Derived::Derived can access Base::member. Therefore, Base::member is initialized by Base::Base before Derived::Derived gets the chance to useBase::member`.

(2) constructors don't allocate memory. That's new's task. Or if the object is a global, the compilers'. The constructor is called with this already pointing to the allocated memory; it need just fill in the members at that location.

In the case of a base and derived constructor, one common implementation inserts the call to the Base constructor in the generated code for the Derived constructor. With single inheritance, the Base and Derived class usually share the same this pointer, so the Derived constrcutor can then pass the same pointer that it got.

(1) [sic] Just like constructors don't allocate memory, destructors don't free it. That's the task of delete - and again, for globals the compiler would do it.

这篇关于如何在C ++中实现构造函数和析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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