In the context of C++ (not that it matters):
class Foo{
private:
int x[100];
public:
Foo();
}
What I've learnt tells me that if you create an instance of Foo like so:
Foo bar = new Foo();
Then the array x is allocated on the heap, but if you created an instance of Foo like so:
Foo bar;
Then it's created on the stack.
I can't find resources online to confirm this.
Strictly speaking, according to the standard the object need not exist on a stack or heap. The standard defines 3 types of 'storage duration', but doesn't state exactly how the storage must be implemented:
Automatic storage duration is typically (nearly always) implemented using the stack.
Dynamic storage duration is typically implemented using the heap (ultimately via
malloc()
), though this can be overridden even by the compiler's user.Static storage duration is what it typically known as globals (or static storage).
The standard has this to say about these things (the following are excerpts form various bits of 3.7 - Storage Duration):
And finally (regarding the array in your example class):
An object of type Foo takes the size of 100 ints stored in sequence. If you create it on the stack, you will be getting it all on the stack. If you do it with new, it'll be on the heap as part of the object.
This is part of the language specification, I'm not sure what your question is.
Yes, the member array
x
will be created on the heap if you create theFoo
object on the heap. When you allocate dynamic memory forFoo
you are asking for memory of lengthsizeof(Foo)
(plus possibly some memory overhead, but let's ignore that for the time being), which in your sample code implies the size of 100int
s. This has to be case for the lifespan of objects of typeFoo
(and their internal data) to cross scopes.If you don't create the
Foo
object on the heap, and the internal array ofFoo
isn't a pointer to which you allocate memory withnew
inFoo
's constructor then that internal array will be created on the stack. Again, this has to be the case in order for the array to automatically be cleaned without anydelete
s when the scope ends. Specifically,will create
y
on the heap regardless of whether aFoo
object was created on the stack or on the heap.You mean
I suppose. That is created in the heap.
Given a slight modification of your example:
Example 1:
Example 2:
Actual sizes may differ slightly due to class/struct alignment depending on your compiler and platform.