c++pointersnullmethodsstandards

Is it legal/well-defined C++ to call a non-static method that doesn't access members through a null pointer?


I recently came across some code of this form:

class Foo
{
public:
    void bar();
    // .. other stuff
};

void Foo::bar()
{
    if(!this) {
        // .. do some stuff without accessing any data members
        return;
    }

    // .. do normal actions using data members
}

It seems like the code explicitly considers the possibility of client code that calls SomeFooPtr->bar() in a case where SomeFooPtr == NULL.

But does it violate the C++ standard to do that?

It occurs to me that it may not violate the standard, because the user defined operator-> returns a pointer — meaning that even if that pointer is NULL, it definitely hasn't been dereferenced (dereferencing a NULL pointer I'm sure is regarded by the standard as illegal or undefined). On the other hand, the semantics of raw pointers don't necessarily have to match the semantics of user defined pointers -- perhaps invoking operator-> on them is considered a dereference even though the compiler won't generate one.


Solution

  • This will probably work on most systems, but it is Undefined Behaviour. Quoth the Standard:

    5.2.5.3

    If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2 [...]

    And:

    5.2.5.1

    A postfix expression followed by a dot . or an arrow ->, optionally followed by the keyword template (14.8.1), and then followed by an id-expression, is a postfix expression. The postfix expression before the dot or arrow is evaluated;58) [...]

    58) This evaluation happens even if the result is unnecessary to determine the value of the entire postfix expression, for example if the id-expression denotes a static member.

    Evaluation of *x where x is a null pointer results in Undefined Behaviour, so yours is clearly a case of UB, before the function is even entered.