Search code examples
c++qtpointersnullptr

When do I need to initialize a pointer to nullptr?


When I am reading some example code of Qt, I usually see they initialize a pointer to nullptr, for example:

QPushButton *startButton = nullptr;

I have some very basic idea of nullptr, but never really used it once since I have started to learn C++. So I wonder why they will initialize a pointer to nullptr instead of just doing like this: QPushButton *startButton;, What is the benefit of doing that and when do I need to initialize a pointer to nullptr?

Thanks in advance.


Solution

  • You need to initialize a pointer before you read it.

    If you only sometimes initialize it to a sensible value before it is read, then initializing it to nullptr at the point of declaration makes sense since then you'll be able to detect nullptr as "not yet initialized to something reasonable".

    Leaving the pointer uninitialized is no good if there's a path in your program that may then read it before it is initialized, since reading an uninitialized variable is Undefined Behaviour.