memset for initialization in C++

后端 未结 2 485
梦如初夏
梦如初夏 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:27

    Don't use memset. It's a holdover from C and won't work on non-PODs. Specifically, using it on a derived class that contains any virtual functions -- or any class containing a non-builtin -- will result in disaster.

    C++ provides a specific syntax for initialization:

    class A {
    public:
       A();
    private:
       int a;
       float f;
       char str[35];
       long *lp;
    };
    
    A::A()
        : a(0), f(0), str(), lp(NULL)
    {
    }
    

    To be honest, I'm not sure, but memset might also be a bad idea on floating-points since their format is unspecified.

提交回复
热议问题