Home >Backend Development >C++ >Where are References to Objects Stored when Created on the Stack vs. the Heap?

Where are References to Objects Stored when Created on the Stack vs. the Heap?

Linda Hamilton
Linda HamiltonOriginal
2024-11-27 01:52:13991browse

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:

  • Automatic storage: If declared locally within a function, the object resides on the stack.
  • Static storage: If declared at namespace or file scope, the object is placed in a dedicated memory region outside the stack or heap.
  • Member variable: If declared as a subobject within another object, it inherits the containing object's storage duration.

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;
  • foo.o has static storage, neither on the stack nor the heap, as foo itself has static storage.
  • f.o has automatic storage, residing on the stack as f has automatic storage.
  • p->o has dynamic storage, on the heap as *p has dynamic storage.
  • pf->o and f.o refer to the same object due to pf pointing directly to 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn