Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

object - C++ stack variables and heap variables

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...