Class Initializer list vs memset(ZeroMemory)

Class Initializer list vs memset(ZeroMemory)

Hi.

When I use class constructor and I need to initialize every member variables as NULL or nullptr. Usually I using the Initializer list. but if there are many variables, It is not good to see like this.

1
2
3
4
5
6
MyClass()
: m_Var1(0)
, m_pVar2(nullptr)
, m_Var3(0)
, ....
{}


but this is very simple.

1
2
3
4
MyClass()
{
   ZeroMemory(this, sizeof(MyClass));   
}


Which one is you guys recommend? and what is the more efficient?
Last edited on
Consider using in-class member initialisers. For example,

1
2
3
4
5
6
7
8
9
10
11
12
struct MyClass
{
    public:
        // https://www.stroustrup.com/C++11FAQ.html#default (redundant)
        // MyClass() = default ;

    private:
        // https://www.stroustrup.com/C++11FAQ.html#member-init
        int m_var1 = 0 ;
        const char* m_pVar2 = nullptr ; // non-owning pointer
        double m_Var3 = 0.0 ;
 };


Be very careful with (if possible avoid) std::memset and the like.
If the object is a potentially-overlapping subobject or is not TriviallyCopyable (e.g., scalar, C-compatible struct, or an array of trivially copyable type), the behavior is undefined.
https://en.cppreference.com/w/cpp/string/byte/memset
JLBorges //

Thank you! I was considering that way, but I thought that do not initialize in header file as possible as I can. but now I think it's the best way.
Don't use the memory functions with the this pointer. It will work with 'simple' objects, but will severely bite you when you come to more complicated classes (eg with dynamic memory objects, virtual member functions etc etc).
seeplus //
I remember that. thank you!
Topic archived. No new replies allowed.