memset for initialization in C++

后端 未结 2 595
梦如初夏
梦如初夏 2020-12-05 10:56

memset is sometimes used to initialize data in a constructor like the example below. Does it work in general ? Is it a good idea in general?

class A {
public         


        
2条回答
  •  感情败类
    2020-12-05 11:33

    It's a terrible idea. You're just tromping over data, paying no heed to how objects should be initialized. If your class is virtual, you're likely to wipe out the vtable pointer as well.

    memset works on raw data, but C++ isn't about raw data. C++ creates abstractions, so if you want to be safe you use those abstractions. Use the initializer list to initialize members.

    You can do it to POD types:

    struct nothing_fancy_here
    {
        bool b;
        int i;
        void* p;
    };
    
    nothing_fancy_here x;
    memset(&x, 0, sizeof(x));
    

    But if you're doing it on this, that means you're in a user-defined constructor and no longer qualify as a POD type. (Though if all your members are POD it might work, as long as none contain 0 as a trap value. I'm sure not sure if any other sources of undefined behavior come into play here.)

提交回复
热议问题