基类和派生类构造函数的内存分配 [英] Memory allocation of base class and derived class constructor

查看:107
本文介绍了基类和派生类构造函数的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建派生类对象时首先为哪个空间分配空间?

For which one the space is allocated first when the derived class object is created?

基类构造函数还是派生类构造函数?

whether base class constructor or derived class constructor?

推荐答案

首先,

  • 分配(您要询问的内存保留)不同于初始化(在其之前)(构造方法的执行,该构造方法本质上是在该内存),以及

  • allocation, the reservation of memory which you’re asking about, is different from and precedes initialization (execution of a constructor that essentially sets suitable values in that memory), and

形式(我们的圣洁标准)和实践中的区别在于,是否需要对大多数派生对象进行连续存储,其中形式上定义了存储区域".可能是不连续的,主要是为了支持多个虚拟继承.

the formal (our Holy Standard) and the in-practice differ on whether memory for a most derived object needs to be contiguous, with the formal defining a “region of memory” as possibly non-contiguous, mostly in order to support multiple virtual inheritance.

也就是说,实际上,派生程度最高的对象是单个连续的内存块,其中包括用于所有基类子对象和数据成员子对象的空间,并且必须对该块进行分配全部一次.

That said, in practice a most derived object is a single, contiguous chunk of memory that includes space for all base class sub-objects and data member sub-objects, and this chunk is necessarily allocated all at once.

分配后继续进行初始化(构造函数调用).如果初始化失败通过抛出异常,new表达式可保证释放.但是,如果所采用的分配函数具有额外的自定义参数(所谓的"placement new"),并且没有相应的释放函数可用,则该保证无效,例如在这种情况下.用于早期Microsoft版本的调试版本MFC类框架(具有讽刺意味的是:初始化失败的程序只会在调试版本中泄漏内存).

Initialization (calls of constructors) proceeds after the allocation. A new expression guarantees a deallocation if initialization fails by throwing an exception. However, this guarantee is voided if the allocation function that’s employed has extra custom arguments (a so called “placement new”) and no corresponding deallocation function is available, as was the case e.g. for debug builds in early versions of Microsoft’ MFC class framework (it was pretty ironic: a program where initialization failed would leak memory only in debug builds…).

这篇关于基类和派生类构造函数的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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