Search code examples
javac++nulljvmmetadata

can 'this' pointer be null in c++ class?


There is a c++ code shown below:

class Metadata : public MetaspaceObj {
    void print_value_on_maybe_null(outputStream* st) const {
    if (this == NULL)
      st->print("NULL");
    else
      print_value_on(tty);
    }
}

I just wonder how could 'this' be NULL in a C++ object.Could be there a possibility?

The code above is excerpted from jdk8/openjdk/hotspot/src/share/vm/oops/metadata.hpp.


Solution

  • In C++ you actually can dereference and call member functions on a NULL pointer.

    Consider:

    Metadata* pointer = nullptr;
    pointer->print_value_on_maybe_null(...);
    

    The code above is valid C++ code, it compiles fine. The problem with this is that it leads to undefined behavior.


    Going back to the code in the question, I think there were, some time in the past, a bug somewhere that cause the member function to be called on a null pointer, and instead of trying to find and fix the root cause of the problem, the authors just added a check for this == NULL.