Explicit initialization of struct/class members

前端 未结 4 1974
清歌不尽
清歌不尽 2021-02-13 15:22
struct some_struct{
    int a;
};
some_struct n = {};

n.a will be 0 after this;

I know this braces form of initialization is inherited from C a

4条回答
  •  难免孤独
    2021-02-13 16:26

    The {0} is C99 apparently.

    Another way to initialize in a C89 and C++ compliant way is this "trick":

    struct some_struct{ int a; };

    static some_struct zstruct;

    some_struct n = zstruct;

    This uses the fact that static variables are pre-initialized with 0'ed memory, contrary to declarations on the stack or heap.

提交回复
热议问题