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.
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.
StaticlyManagedObject
is a misnomer. It's allocated dynamically, same as the parent object.
The nested class members use the same allocation method as the parent object, unless they're specifically marked static
, in which case they aren't allocated at the time of object creation, or they're specifically allocated dynamically in constructors.
Whether a member of your class is another class, or an elementary data type:
class DynamiclyManagedObject
{
StaticlyManagedObject _staticlyManagedObject;
int some_integer;
};
It doesn't matter whether the class member is another class, or an elementary data type, such as an int
. Both "_staticlyManagedObject" and "some_integer" are completely identical to each other, except for their type (of course, that's not exactly a trivial attribute). One is an int
, the other one is some other class. The type of a class member does not affect its scope. Either the entire class is dynamically allocated, or it's not. Or it's allocated in the automatic scope (on the stack, as you say).
The only exception to the rule is a static
class member:
class DynamiclyManagedObject
{
StaticlyManagedObject _staticlyManagedObject;
int some_integer;
static std::string some_string;
};
The rules are different for some_string
. Note that this is a real static class member, and not a class member whose type happens to be StaticallyManagedObject
.
上一篇: 为什么我不应该设置布局
下一篇: 堆分配的对象是否将其成员分配到堆栈上?