5

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.

asked Dec 25, 2017 at 13:27
2
  • 1
    It is UB to use uninitialized variable. Better to initialize them when declaring them. (You can then test for nullptr). Commented Dec 25, 2017 at 13:33
  • 1
    OT: Do you even need the pointer to the button? With my 9+ years of Qt development at work I find that most of the time in Qt that you don't need the pointer because of signals and slots. If on a rare occasion you need the pointer you can use findChildren<QPushButton*>() on its parent. Commented Dec 25, 2017 at 14:39

2 Answers 2

9

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.

answered Dec 25, 2017 at 13:34
Sign up to request clarification or add additional context in comments.

Comments

3

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.

answered Dec 25, 2017 at 13:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.