Many of the comments on How to ask a question which is similar to other downvoted and closed questions? asked for details re: the specific question I was asking, but since that question has already been answered in a generic fashion, I felt it best to create a separate question.
The question I want to ask on SO is:
Ignoring user-defined operator overloads, are there any cases where
if (!x)
would behave differently fromif (x == nullptr)
e.g. Are there any types in the standard library for which
!x
would behave differently fromx == nullptr
A quick google search returns many similar questions already on SO, many of which have been closed. to name a few:
- Condition checking: if(x==0) vs. if(!x)
- Checking for NULL pointer in C/C++
- C/C++ `!a` vs `a==0`
- Do you prefer "if (var)" or "if (var != 0)"?
I believe my question to be different from the existing questions for the following reasons:
nullptr
vs0
/NULL
- there is the potential for a different sequence of type conversions. I don't know enough about implicit conversions to figure out whether this could indeed change behaviour though.
x == 0
(andx == NULL
when NULL is not defined as nullptr) is not supported by some of the standard library types such asstd::shared_ptr
, but every one I checked supportedx == nullptr
andx != nullptr
- I'm not interested in the obvious case of when a user defines operator overloads such that
!((bool)x)
andx == nullptr
are different. - I'm not asking for personal preferences, I'm interested in whether there are any objective differences between the two choices
std::optional<T*>
is an answer to your question. Givenstd::optional<T*> x{nullptr};
,!x
returnsfalse
, whilex == nullptr
returnstrue
.