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?
The difference is important with PODs (basically, all built-in types like
int,bool,doubleetc. 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 simplewill leave
objuninitialized, whileT()default-initializes the object. Sois a good way to ensure that an object is properly initialized.
This is especially helpful in template code, where
Tmight either a POD or a non-POD type. When you know thatTis not a POD type,T obj;suffices.Addendum: You can also write
(and avoid initialization of the allocated object if
Tis a POD).