I see Q_NULLPTR
being used liberally in Qt source code and examples, but I have found no documentation for what it is exactly and when it should be used.
For example in this official demonstration of the new Qt SerialBus module added in the new Qt v5.6:
if (!m_canDevice->connectDevice()) { delete m_canDevice; m_canDevice = Q_NULLPTR;
Did this serve the purpose of nullptr
prior to that being added in C++11? If so, now that we have C++11, should I be using Q_NULLPTR
?
PS: I tried searching the Qt source code for the definition of the macro but failed to find it.
As I mentioned above, the general rule of thumb that I recommend is that you should start using nullptr whenever you would have used NULL in the past. As a reminder, since C++11, NULL can be either an integer literal with value zero, or a prvalue of type std::nullptr_t .
nullptr is a keyword that represents zero as an address (its type is considered a pointer-type), while NULL is the value zero as an int . If you're writing something where you're referring to the zero address, rather than the value zero, you should use nullptr .
nullptr is of type std::nullptr_t and so the constructor be overloaded. This means the fact that it is null is encoded in the type, so it can be theoretically faster by avoiding a conditional. Pointers obviously don't have overloaded constructors so whether you use 0 or nullptr is irrelevant.
Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.
Q_NULLPTR
is a macro, that is replaced as nullptr
if compiler supports c++11 and as NULL
(which is replaced as 0
) if it doesn't. If you use c++11, you can write nullptr
instead; use NULL
if you don't.
Did this serve the purpose of nullptr prior to that being added in C++11? If so, now that we have C++11, should I be using Q_NULLPTR?
Yes (somewhat) and No respectively.
C++ was quite lacking back in the days, so Qt had its own stuff, which later became obsolete as C++ caught up on the features.
That being said, Q_NULLPTR
is (was) not functionally the same as nullptr
, (as Andrei noted, if C++11 is supported it expands to nullptr
) it didn't give you the type safety, just syntax "sugar". It illustrated the intent to the person reading the code, not to the compiler as nullptr
does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With