堆分配的对象会在堆栈上分配其成员吗?

编程入门 行业动态 更新时间:2024-10-28 02:27:43
本文介绍了堆分配的对象会在堆栈上分配其成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让我们考虑这个例子.

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.

更多推荐

堆分配的对象会在堆栈上分配其成员吗?

本文发布于:2023-08-04 00:56:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1291491.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分配   堆栈   会在   对象   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!