Home >Backend Development >C++ >Where are References to Objects Stored when Created on the Stack vs. the Heap?
Object Creation on the Stack or Heap:
The question arises: when creating an object on the stack versus the heap, where are references to those objects actually stored?
In C , object storage is determined by its context, namely its storage duration:
Object o creates an object with:
Object* o creates a pointer with automatic storage.
Pointers are allocated on the stack like any other object. Their storage duration is determined by their context, not by the initialising expression.
For example, in the code fragment below:
struct Foo { Object o; }; Foo foo, f; Foo* p = new Foo; Foo* pf = &f;
In summary, object storage location depends solely on its context, while pointers are always allocated on the stack but can reference objects of various storage durations.
The above is the detailed content of Where are References to Objects Stored when Created on the Stack vs. the Heap?. For more information, please follow other related articles on the PHP Chinese website!