堆分配的对象会在堆栈上分配其成员吗? [英] Will heap allocated objects have their members allocated on the stack?

查看:48
本文介绍了堆分配的对象会在堆栈上分配其成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑这个例子.

class StaticlyManagedObject
{
   //some class members....
}
class DynamiclyManagedObject
{
   StaticlyManagedObject _staticlyManagedObject; //is this still allocated at the stack?

}

class Foo
{
  DynamiclyManagedObject * _dynamiclyManagedObject; //will be allocated in the heap.
  Foo()
  {
      _dynamiclyManagedObject = new DynamiclyManagedObject();
  }
}

有人告诉我,当我们在C ++中不使用动态内存管理时,事情是在堆栈中分配的,因此我们不需要内存管理.

I have been told that when we don't use dynamic memory management in C++, things are allocated in stack and we don't need memory management.

但是,在此示例中.我们有一个动态分配的对象,称为DynamiclyManagedObject.我在Foo构造函数中实例化此对象.我的问题是DynamiclyManagedObject的静态管理数据成员会发生什么情况?

However, in this example. we have a dynamically allocated object which is called DynamiclyManagedObject I instantiate this object within the Foo constructor. My question is what happens to the statically managed data member of the DynamiclyManagedObject?

是否仍在堆栈上创建它,还是..由于在堆中创建了DynamiclyManagedObject,所以它的每个数据成员最终都进入了堆.

Is it still created on the stack or.. because of the fact that DynamiclyManagedObject created in the heap, every data member of it ends up into the heap.

推荐答案

子对象的存储期限与作为其一部分的完整对象的储存期限相同.如果动态分配了 DynamiclyManagedObject 的实例,则在销毁 DynamiclyManagedObject 时,销毁 StaticlyManagedObject 成员.

A subobject has the same storage duration as the complete object it is a part of. If an instance of DynamiclyManagedObject is dynamically allocated, then the StaticlyManagedObject member will be destroyed when the DynamiclyManagedObject is destroyed.

非正式地,您可能会说,当且仅当完整对象在堆上时,子对象才会在堆上.但是,存储期限是技术上谈论它的正确方法.堆和栈是实现细节.

Informally, you might say that the subobject will be on the heap if and only if the complete object is on the heap. However, storage duration is the technically correct way to talk about it; heap and stack are implementation details.

这篇关于堆分配的对象会在堆栈上分配其成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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