The location of the elements of the object

Possible duplicate:
Are data members distributed in the same memory space as their C ++ objects?

If I declare an object like this:

void main() { MyClass class; } 

it will be created automatically on the stack.

What happens if I do this:

 class MySecondClass { private: MyClass class; } 

Will the item be created on the stack? If so, what happens if MySecondClass is created via new ? Will this item still be on the stack?

0
source share
2 answers

Will the item be created on the stack?

Yes.

If so, what happens if MySecondClass is created via new ? Will this item still be on the stack?

Not. It will be stored along with the rest of the object, "on the heap" or wherever you are in a free store, or wherever the object is dynamically allocated (it could be some kind of memory pool or something else).

It is worth noting here that the terms "stack" and "heap" are usually used incorrectly. What you are really asking is the following:

Does member have auto-storage time? Yes.

Will it do this even if the encapsulation object has a dynamic storage duration? No β€” the dynamism of an encapsulating object is, in a sense, β€œinherited”.

[C++11: 3.7.5]: The storage duration of member subobjects, base class subobjects and array elements is their complete object (1.8).

The practical place in memory will in any case be the stack and free storage ("heap"), respectively, and this does not really matter.

And by the way, main should have an int return type.

+5
source

Yes, a member is created on the stack.

If you create a new MyClass object using "new", resources will be allocated on the heap.

+1
source

All Articles