How to initialize a struct to 0 in C++

前端 未结 3 1299
梦毁少年i
梦毁少年i 2020-12-10 09:52

Here is a related C answer that doesn\'t work (as a zero initializer for a struct) on C++: Initializing a struct to 0. One of the solutions presented is this:



        
3条回答
  •  隐瞒了意图╮
    2020-12-10 10:46

    Objects in C++ are given the ability to control the values of any subobjects within them. As such, C++ has no mechanism that will force zero-initialization onto any object in general.

    Objects with no user-provided constructors or default member initializers can undergo zero-initialization in two cases: if the variable is declared static, or if the object is being value-initialized. There are multiple syntaxes that will provoke value initialization of an object, including T(), T{}, and T t = {};, where applicable.

    But other than that, if the creator of the type of an object does not want it to be zero-initialized, then you cannot impose that upon the object. You can ask for value-initialization or default-initialization, but whether either of these will invoke zero-initialization depends on the type.

提交回复
热议问题