Where does the memory come from to initialize a C++ object without the new keyword? -
consider code snippet:
classname* p; p = new classname;
as understand it, allocating memory heap store *p
.
but consider:
classname c;
question: if not heap, memory c
come from?
question: if not heap, memory c come from?
from stack (or in case of global variable or function 'static' variable, statically allocated region exists independently of both heap , stack).
strictly speaking, c++ has no concept of heap or stack (other data structures in standard library, fundamentally different "the" heap , stack prevalent mechanisms used allocation of memory running programs); exact mechanism allocation , management of memory not specified. in practice, there 2 ways program allocate memory @ run time on systems: heap (which built on memory chunks obtained operating system), or stack (the same stack used store return address , save temporary values when functions called).
memory stack allocated when (or before) program begins execution, , needs contiguous. memory heap obtained dynamically , not need contiguous (though in practice heap memory allocated in contiguous chunks).
note first example:
classname* p; p = new classname;
... embodies 2 allocations: 1 classname
object (dynamic storage, allocated on heap) , 1 pointer variable p
(automatic storage, allocated on heap).
in practice, local variables not require stack allocation - values can kept in registers (or in cases, storage can optimised away altogether, if value unused or compile-time constant). , theoretically, heap allocations can potentially optimised away.
Comments
Post a Comment