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.
2 Answers 2
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.
Comments
When do I need to initialize a pointer to nullptr?
In situations where you cannot initialize a pointer to an address of an object (possibly because that object does not yet exist, or perhaps only ever exists conditionally), but you need to be able to check whether the pointer does point to an object or not.
You can know that a pointer that points to null definitely does not point to an existing object. If you define the post-conditions and invariants of your program correctly, you'll be able to prove that a pointer always points to either null, or a valid object.
Null isn't the only option. Another option is to initialize to a static object that always exists. This is typical solution in node based (i.e. link based) data structures where that static object is called a sentinel node.
nullptr).