-4

This C++ code works for my platform and compiler (Windows, GCC 4.7):

#include <stdio.h>

class A {
public:

    /* ... */

    int size() const
    {
        if ( this == NULL ) {
            return 0;
        }
        return m_size;
    }

private:
    int m_size;
};

int main()
{
    A* a = NULL;

    printf( "%d\n", a->size() );
}

But is this code valid standard C++ and portable? Is it Ok for method to accept this == NULL?

user3123061
  • 757
  • 5
  • 14

1 Answers1

5

No, that's not OK. Any dereference of a NULL pointer is undefined behavior. It happens to work because it's not a virtual function (therefore there's no jump through the object's vtable), but that's not an excuse for doing what you're doing.

Michael Kohne
  • 11,888
  • 3
  • 47
  • 79