zeroing derived struct using memset

后端 未结 4 999
耶瑟儿~
耶瑟儿~ 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:31

    The standard does not "frown on the practice"; it gives undefined behavior.

    For example:

    this + sizeof (Base)
    

    There is nothing in the C++ standard that says that this expression resolves to a pointer to Derived. Indeed, since the type of this is Derived * const, then what you've done is pointer arithmetic. C++ will try to add to it as though this were a pointer to an array of Derived, the equivalent of this[sizeof(Base)]. Which probably isn't what you wanted.

    Do not walk the dark corridors of undefined behavior if you're not sure how to do it right.

    Most importantly of all, even if you pointer gymnastics to actually work, your code becomes very fragile. It may work on this version of your compiler, but it will fail on a later one. Doing something simple like adding a virtual function to Base will cause chaos in your code, as you will destroy the vtable pointer.

    It seems to me that you have a couple of problems:

    1. Needless derivation. If Base has nothing virtual in it, why are you publicly deriving from it?
    2. A fat interface. If you see a class start to have hundreds of members, then it's probably doing too much.

提交回复
热议问题