Initializing an object to all zeroes

后端 未结 12 637
离开以前
离开以前 2020-12-03 01:27

Oftentimes data structures\' valid initialization is to set all members to zero. Even when programming in C++, one may need to interface with an external API for which this

12条回答
  •  误落风尘
    2020-12-03 02:25

    I found a good solution to be:

    template void my_zero(T& e) {
        static T dummy_zero_object;
        e = dummy_zero_object;
    }
    
    my_zero(s);
    

    This does the right thing not only for fundamental types and user-defined types, but it also zero-initializes types for which the default constructor is defined but does not initialize all member variables --- especially classes containing non-trivial union members.

提交回复
热议问题