Possible Duplicate:
When does invoking a member function on a null instance result in undefined behavior?
Anything like this:
class Class {
public:
void Method()
{
//empty;
}
};
Class* object = 0;
object->Method();
is undefined behavior in C++ because calling non-static member functions via null pointers is formally illegal. See this answer for a detailed explanation full of quotes from the C++ Standard. I’m well aware of the theoretical part and this question is not about theory and so it’s not a duplicate of that question.
In all implementations I’m aware of the code above or some equivalent thereof doesn’t cause any observable problems – since the member function doesn’t access the object the method will be called just fine.
May I have any real-life example in which the same setup causes practical observable problems?
Simple:
Let us say that
foodoes not access any non-static attribute ofObject(ie,x).The problem is that because formally
o->foo()is undefined behavior ifois null, then it is obvious thatois not null. Therefore the check is redundant.The function is thus optimized:
Reversing the order does not change anything:
is still optimized:
Sometimes referred to as the Time Travel Clause of Undefined Behavior by some SO members.
For more information, check out Chris Lattner’s serie on Undefined Behavior:
Your specific concern is addressed in
2/3.Whether this actually fails depend on the compiler you use, the optimization passes you specify and the order in which they run.
Do you really want to depend on all that 😡 ?
Of course, one would argue that’s it is pointless to have a function member that does not access any state of the object… so the question itself is of little value in practice (but interesting for its theoretical aspects).