Explicit initialization of struct/class members

谁说胖子不能爱 提交于 2020-01-22 13:35: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 and is supported for compatibility with C programs, but this only compiles with C++, not with the C compiler. I'm using Visual C++ 2005.

In C this type of initialization

struct some_struct n = {0};

is correct and will zero-initialize all members of a structure.

Is the empty pair of braces form of initialization standard? I first saw this form of initialization in a WinAPI tutorial from msdn.


回答1:


The empty braces form of initialization is standard in C++ (it's permitted explicitly by the grammar). See C Static Array Initialization - how verbose do I need to be? for more details if you're interested.

I assume that it was added to C++ because it might not be appropriate for a 0 value to be used for a default init value in all situations.




回答2:


It is standard in C++, it isn't in C.

The syntax was introduced to C++, because some objects can't be initialized with 0, and there would be no generic way to perform value-initialization of arrays.




回答3:


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.




回答4:


I find the following link to be very informative on this particular issue

  • http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/strin.htm


来源:https://stackoverflow.com/questions/3003574/explicit-initialization-of-struct-class-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!