简体   繁体   中英

C++: Should I initialize pointer members that are assigned to in the constructor body to NULL?

Suppose I have:

// MyClass.h
class MyClass
{
  public:
    MyClass();

  private:
    Something *something_;
}

// MyClass.cpp
MyClass::MyClass()
{
  something_ = new Something();
}

Should I initialize something_ to NULL (or 0) in the constructor initialization list of the MyClass constructor? Or is that not necessary because I'm assigning to it in the body of the constructor? What is the recommended practice?

Generally you only assign it once, in the initialization list or the body, unless the body initialization may or may not happen, or has prerequisite code:

MyClass::MyClass() 
{
   //this code must happen first
   // _now_ max is known
   something_ = new Something(max);
}

MyClass::MyClass() 
{
   if (max) 
       something_ = new Something(max);
   else
       something_ = NULL;
}

MyClass::MyClass() 
    : something_(new Something()) 
//as pointed out in the comments, use smart pointers
{
}

Generally speaking - no. But if somewhere in your constructor pointer is used before it has been initialized then you get undefined behaviour. However, the biggest problem that you have is this - if exception is thrown in constructor, its destructor is not called. So imagine you have two pointers to objects and allocation of the first object succeeds while the second allocation fails, in that case you end up with a resource leak. This can be solved by using "smart" pointers. But in that case they will be initialized in initialization list, and if you don't want to assign value to them twice then you better allocate memory in there rather than in constructor body.

Not necessary, especially if you immediately initialize in the constructor body, however if initialization is not so obvious then why not NULL it to avoid accidental access to uninitialized variable.

  • minimal performance overhead
  • saves so much debugging/troubleshooting time with crazy bug hunting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM