zeroing derived struct using memset

后端 未结 4 961
耶瑟儿~
耶瑟儿~ 2021-01-16 14:36

I want to zero out all members of a derived structure.

There are hundreds of members and more are added every once in a while so I feel that initializing them explic

4条回答
  •  天涯浪人
    2021-01-16 15:16

    This assumes that the Base base class subobject is located at the beginning of Derived. This won't work if you add another base class.

    Further, your code is wrong: pointer arithmetic is performed in terms of objects, not in terms of bytes. You need to use reinterpret_cast(this) to perform the arithmetic in terms of bytes. In any case, you still shouldn't do this.

    Consider the following, non-ugly, standards-conforming approach utilizing value initialization:

    struct Derived : public Base
    {
        struct DerivedMembers { /* ... */ }
    
        DerivedMembers data;
    
        Derived() : data() { }
    };
    

    As long as DerivedMembers has no constructor, this will value initialize each of the data members of data, which look like it's exactly the behavior you want.

    Or, if you want the members to be accessible without using a "data" member variable, consider using another base class:

    struct DerivedMembers { /* ... */ }
    
    struct Derived : Base, DerivedMembers
    {
        Derived() : DerivedMembers() { }
    };
    

提交回复
热议问题