Nusakan Nusakan - 3 months ago 8
C++ Question

Will heap allocated objects have their members allocated on the stack?

Let's consider this example.

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();
}
}


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.

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?

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.

Answer

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.

Comments