How to default-initialize local variables of built-in types in C++?

后端 未结 5 802
春和景丽
春和景丽 2021-01-06 20:34

How do I default-initialize a local variable of primitive type in C++? For example if a have a typedef:

typedef unsigned char boolean;//that\'s Microsoft RPC         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 21:13

    You can emulate that behaviour by the following:

    boolean x = boolean();
    

    or, more general,

    T x = T();
    

    This will default-initialize x if such a default-initialization exists. However, just writing T x will never do the trick for local variables, no matter what you do.

    You can also use placement-new to invoke a “constructor”, even for POD:

    T x;
    new (&x) T();
    

    Notice that this code produces undefined behaviour for non-POD types (in particular for types that have a non-trivial destructor). To make this code work with user-defined types, we first need to call the object’s destructor:

    T x;
    x.~T();
    new (&x) T();
    

    This syntax can also be used for PODs (guaranteed by §§5.2.4/12.4.15) so the above code can be used indiscriminately for any type.

提交回复
热议问题