Search code examples
c++memset

Using memset this way is good?


I am using memset this way:

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

    A::A()
    {
       memset(this, 0, sizeof(*this));
    }
}

Should I use this way? Why and Why not? Is there a better way? Need some guidance..


Solution

  • This is generally a bad idea.

    If someone adds a new member to the class it could break horribly if the type of the new member has a proper constructor and memset is not suitable.

    Formally, according to the standard your user-defined constructor means that A is not a POD type (or trivially-copyable type in C++11) and so it is not safe to use memset or memcpy on it.

    There are several ways to do this safely:

    A::A() : a(), f(), str(), lp()
    { }
    

    Alternatively, do not add a constructor and value-initialize instances of the type:

    A a = A();
    

    Or, group the POD members together and value-initialize them all at once in the constructor:

    class A {
    public:
      A();
    private:
      struct Data {
        int a;
        float f;
        char str[35];
        long *lp;
      };
      Data data;
    };
    
    A::A() : data()
    { }
    

    In general it's better to use value-initialization in C++ and rely on the compiler to do the equivalent of the memset (or calling default constructors) rather than expicitly using memset yourself. The code will be less fragile and easier to maintain.