I was recently reading Programming: Principles and Practice Using C++ (2nd Edition), and I came upon this snippet inside a function for inserting into a linked list (Page 619):
if (n==nullptr) return this;
if (this==nullptr) return n;
The first check seems fine, but the second check is very confusing to me. The question that immediately came to my mind is how this == nullptr
can ever be true, considering that this
would only equal nullptr
if the object was instantiated as nullptr
. Since this snippet is in a member function, one would have to dereference a null pointer to access it, which is undefined behavior. To confirm this, I created a small snippet:
#include <iostream>
class Test
{
public:
Test() = default;
void checkSelf()
{
if (this == nullptr)
{
std::cout << "This was nullptr.\n";
}
else
{
std::cout << "This was not nullptr.\n";
}
}
};
int main()
{
Test* test; // Uninitialized pointer
test->checkSelf(); // Outputs 'This was nullptr.'
Test* test2 = nullptr;
test2->checkSelf(); // Outputs 'This was nullptr.'
Test* test3 = new Test{}; // Outputs 'This was not nullptr.'
test3->checkSelf();
delete test3;
}
And just as I expected, only when the pointer was uninitialized as in the first case (Well actually not expected here), or when it was set to nullptr
as in the second case did the check evaluate to true
inside the member function. However, since both examples where this was true were examples of undefined behavior, it makes no sense that the check could ever be true in a well-formed program. Thus, Can the check this == nullptr
ever be true without invoking UB?