C++ stack variables and heap variables

后端 未结 2 1261
悲哀的现实
悲哀的现实 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:11

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

提交回复
热议问题