Pointer Member Variable Initialization in C++ Classes

后端 未结 4 1998
梦谈多话
梦谈多话 2020-12-17 09:34

This is going to sound so basic as to make one think I made zero effort to find the answer myself, but I swear I did search for about 20 minutes and found no answer.

4条回答
  •  猫巷女王i
    2020-12-17 10:29

    the value of any uninitialized pointer is always garbage, it's some random memory address.

    in your constructors, you can use initializer lists to initialize your pointer

    simply

    MyClass::MyClass() : myPointer(nullptr)
    {
    }
    

    trying to reference an uninitialized pointer triggers undefined behavior. so ALWAYS initialize your pointer.

提交回复
热议问题