Consider the code snippet:
ClassName* p;
p = new ClassName;
As I understand it, we are allocating memory from the heap to store *p
.
But now consider:
ClassName C;
Question: If not from the heap, where does the memory for C
come from?
Consider the code snippet:
ClassName* p;
p = new ClassName;
As I understand it, we are allocating memory from the heap to store *p
.
But now consider:
ClassName C;
Question: If not from the heap, where does the memory for C
come from?
As I understand it, we are allocating memory from the heap to store
*p
.
More correctly worded, the object created by new
has dynamic storage duration.
If not from the heap, where does the memory for
C
come from?
It has automatic storage duration.
See C++ standard §3.7/1.
Talking about "stack" or "heap" takes you on the compiler-implementation level. You are generally not interested in how the C++ compiler makes the different kinds of storage duration work but are only interested in their semantics.
Question: If not from the heap, where does the memory for C come from?
From the stack (or in the case of a global variable or function 'static' variable, from a statically allocated region that exists independently of both the heap and the stack).
Strictly speaking, C++ has no concept of heap or stack (other than as data structures in the standard library, which are fundamentally different to "the" heap and stack that are the prevalent mechanisms used for allocation of memory by running programs); the exact mechanism for allocation and management of memory is not specified. In practice, there are two ways for a program to allocate memory at run time on most systems: from the heap (which is itself built on memory chunks obtained from the operating system), or from the stack (the same stack that is used to store the return address and save temporary values when functions are called).
Memory for the stack is usually allocated when (or just before) the program begins execution, and it usually needs to be contiguous. Memory for the heap is usually obtained dynamically and does not normally need to be contiguous (though in practice heap memory is often allocated in contiguous chunks).
Note that your first example:
ClassName* p;
p = new ClassName;
... actually embodies two allocations: one for the ClassName
object (dynamic storage, allocated on the heap) and one for the pointer variable p
(automatic storage, allocated on the heap).
In practice, local variables will not always require stack allocation - their values can sometimes be kept in registers (or in some cases, the storage can be optimised away altogether, especially if the value is unused or is a compile-time constant). And theoretically, heap allocations can also potentially be optimised away.