sirg3 sirg3 - 1 year ago 70
C++ Question

C++ static const access through a NULL pointer

class Foo {
static const int kType = 42;

void Func() {
Foo *bar = NULL;
int x = bar->kType;
putc(x, stderr);

Is this defined behavior? I read through the C++ standard but couldn't find anything about accessing a static const value like this... I've examined the assembly produced by GCC 4.2, Clang++, and Visual Studio 2010 and none of them perform a dereference of the NULL pointer, but I'd like to be sure.

Answer Source

You can use a pointer (or other expression) to access a static member; however, doing so through a NULL pointer unfortunately is officially undefined behavior. From 9.4/2 "Static members":

A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (5.2.5) to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object-expression is evaluated.

Based on the example that follows:

class process {
    static void reschedule();

process& g();

void f()
    process::reschedule();   // OK: no object necessary
    g().reschedule();        // g() is called

The intent is to allow you to ensure that functions will be called in this scenario.