Why would code explicitly call a static method via a null pointer?

C++PointersStatic MembersUndefined BehaviorDereference

C++ Problem Overview


I've seen code like this in a couple of old projects:

class Class {
    static void Method() {}
};

((Class*)0)->Method();

This code contains undefined behavior because it includes dereferencing a null pointer (no matter what happens afterwards). It really makes no sense - the cast is there to feed the type name to the compiler and whoever wrote the code above could have written this instead:

Class::Method();

and the latter would be okay.

Why would anyone write the former code? Is it a known idiom from some good old days or what?

C++ Solutions


Solution 1 - C++

Static member functions were added into C++ in 1989, in Release 2.0 of the AT&T C++ Language System (pre-standardisation). Prior to that, the static keyword could not be used to declare static member functions, so code authors used workarounds, principally the one you have observed of indirecting a null pointer.

In the Selected Readings accompanying version 2.0 of the AT&T C++ Language System, in section 1-22, Stroustrup writes:

> It was also observed that nonportable code, such as: > > ((X*)0)->f(); > > was used to simulate static member functions. This trick is a time bomb because sooner or later someone will make an f() that is used this way virtual and the call will fail horribly because there is no X object at address zero. Even where f() is not virtual such calls will fail under some implementations of dynamic linking.

Your code was written to compile under Cfront 1.0 or by someone who was not aware at the time of the addition of static member functions to the language.

The annotation of the member function with static is indeed a puzzle, as Cheers and hth. - Alf has observed; Cfront 1.0 would have rejected that code with:

error:  member Method() cannot be static

so it cannot have been there initially. I think Potatoswatter is most likely correct; static was added at a later date to document and enforce the static method attribute of Method, once a C++ 2.0 compiler could be guaranteed to be available, but without the calling code being updated. To confirm this you'd need to interview the original programmer(s) or at least examine source control history (if any exists).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsharptoothView Question on Stackoverflow
Solution 1 - C++ecatmurView Answer on Stackoverflow