C++ stack variables and heap variables

后端 未结 2 1255
悲哀的现实
悲哀的现实 2020-12-15 10:33

When you create a new object in C++ that lives on the stack, (the way I\'ve mostly seen it) you do this:

CDPlayer player;

When you create a

2条回答
  •  粉色の甜心
    2020-12-15 11:02

    When you create a new object in C++ that lives on the stack, (…) you do this:

    CDPlayer player;
    

    Not necessarily on the stack: variables declared in this way have automatic storage. Where they actually go depends. It may be on the stack (in particular when the declaration is inside a method) but it may also be somewhere else.

    Consider the case where the declaration is inside a class:

    class foo {
        int x;
    };
    

    Now the storage of x is where ever the class instance is stored. If it’s stored on the heap, then so is x:

    foo* pf = new foo(); // pf.x lives on the heap.
    foo f; // f.x lives where f lives, which has (once again) automatic storage.
    

提交回复
热议问题