C++ stack variables and heap variables

2019-01-23 07:17发布

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 an object on the heap you call new:

CDPlayer* player = new CDPlayer();

But when you do this:

CDPlayer player=CDPlayer();

it creates a stack based object, but whats the difference between that and the top example?

3条回答
Bombasti
2楼-- · 2019-01-23 07:36

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.
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-23 07:42

The difference is important with PODs (basically, all built-in types like int, bool, double etc. plus C-like structs and unions built only from other PODs), for which there is a difference between default initialization and value initialization. For PODs, a simple

T obj;

will leave obj uninitialized, while T() default-initializes the object. So

T obj = T();

is a good way to ensure that an object is properly initialized.

This is especially helpful in template code, where T might either a POD or a non-POD type. When you know that T is not a POD type, T obj; suffices.

Addendum: You can also write

T* ptr = new T; // note the missing ()

(and avoid initialization of the allocated object if T is a POD).

查看更多
Bombasti
4楼-- · 2019-01-23 07:54
CDPlayer* player = new CDPlayer();

What this actually does is create a pointer on the stack and makes it point to a CDPlayer object allocated on the heap.

查看更多
登录 后发表回答