Object creation on the stack/heap?

The following code creates an object on the stack:

Object o;

When creating an object on the heap we can use:

Object* o;

o = new Object();

rather than:

Object* o = new Object();

When we split the heap object-creation over two lines and call the constructor on the second line ( o = new object() ), does this mean in the first line ( Object* o ) the pointer was created on the stack? So Object o puts the object on the stack, whereas Object* o puts the pointer to a future object on the stack?

My second question involves if the two lines of code were called outside of a class. I recently read (Global memory management in C in stack or heap?) that global variables are not contained on the stack/heap but actually another part of memory? If this is the case, would Object* o create a pointer which would sit in this other part of the memory and it points to the heap object?


Actually, neither statement says anything about heap or stack:

Object o;

creates an object with automatic storage meaning that the storage location is determined by the context in which the object is declared: If the code is in a function, this happens to be the call stack. But the line could also be a class member or, as you've noted, outside of a function / class.

To illustrate why this is different:

struct Foo {
    Object o;
};

Foo* pf = new Foo();

Now the object pf->o is created on the heap, not on the stack, even though (or rather, because) it has automatic storage.

Conversely,

Object* p;

simply declares a pointer, nothing more. The pointer's storage is indistinguishable from any other object's: it has automatic storage. Furthermore, the initialising expression has no effect on the variable storage.

What the pointer points to is a completely different matter. It might be a heap-allocated object (using new for instance) or it might point to another automatically allocated object. Consider:

Object o;
Object* p = &o;

C++ offers three different ways to create objects:

  • Stack-based such as temporary objects
  • Heap-based by using new
  • Static memory allocation such as global variables and namespace-scope objects
  • Consider your case,

    Object* o;
    o = new Object();
    

    and:

    Object* o = new Object();
    

    Both forms are the same. This means that a pointer variable o is created on the stack (assume your variables does not belong to the 3 category above) and it points to a memory in the heap, which contains the object.


    The two forms are the same with one exception: temporarily, the new (Object *) has an undefined value when the creation and assignment are separate. The compiler may combine them back together, since the undefined pointer is not particularly useful. This does not relate to global variables (unless the declaration is global, in which case it's still true for both forms).

    链接地址: http://www.djcxy.com/p/13864.html

    上一篇: 哪一个会堆栈或堆?

    下一篇: 在堆栈/堆上创建对象?