I started this discussion here:https://groups.google.com/forum/#!topic/comp.lang.c++/AspSSs0SaIoThe book Programming: Principles and Practice with C++ 2nd edition presents the following code, Page 620 (2nd edition, fourth print):
//------------code1----------------
Link* Link::insert(Link* n) // insert n before this object; return n
{
if (n==nullptr) return this;
if (this==nullptr) return n;
n–>succ = this; // this object comes after n
if (prev) prev–>succ = n;
n–>prev = prev; // this object’s predecessor becomes n’s predecessor
prev = n; // n becomes this object’s predecessor
return n;
}
See this line:
if (this==nullptr) return n;
It is saying that you can call the insert method using as "Link *" a pointer to null.
Example:
Link *p = nullptr; // EMPTY LIST
p = p->insert(new Link{"Athena"}); // INSERTING ATHENA
// p is pointing to Athena now.
// p-->[athena]
The problem is: Several peoples insist to say that it is UB:
https://www.google.com/#q=this+null+c%2B%2BWhen in fact the standard is not very clear on that.
These people say that the standard should be clearer in saying that this is UB.
What I am trying to say with this post is the opposite. Of course there are situations (most cases) where dereference a null pointer is a wrong code.
But it would be a terrible mistake to consider that "code1" UB, since it is not.
Being more clear:
There are situations where dereference null pointer is obviously a wrong code.
but
There are situations where dereference null pointer is just a good technique.