Is this C++ structure initialization trick safe?

前端 未结 16 1156
有刺的猬
有刺的猬 2020-12-23 17:56

Instead of having to remember to initialize a simple \'C\' structure, I might derive from it and zero it in the constructor like this:

struct MY_STRUCT
{
            


        
16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 18:30

    This is a perfect example of porting a C idiom to C++ (and why it might not always work...)

    The problem you will have with using memset is that in C++, a struct and a class are exactly the same thing except that by default, a struct has public visibility and a class has private visibility.

    Thus, what if later on, some well meaning programmer changes MY_STRUCT like so:

    
    struct MY_STRUCT
    {
        int n1;
        int n2;
    
       // Provide a default implementation...
       virtual int add() {return n1 + n2;}  
    };
    

    By adding that single function, your memset might now cause havoc. There is a detailed discussion in comp.lang.c+

提交回复
热议问题