Search code examples
visual-c++c++-climanaged-c++object-reference

How to check a "NULL object reference" in Managed C++?


I come across some MC++ code like this:

__gc class ClassA
{
Puclic:
     ClassB GetClassB();
}

__gc class ClassB
{
 Public:
    int Value;
}

int main()
{
    ClassA^ a = gcnew ClassA();
    ClassB^ b = a->GetClassB();

    int c = b->Value;
}

Isn't it important to check whether b is NULL before access to its value? I tried if(b == NULL), but it dosen't work.

Or it's really not necessary to do the check? however I can hardly believe it...

PS: I only want to know whether the "Reference" itself could be NULL here. Whether the content of class B is null isn't important.


Solution

  • This program is both syntactically and semantically correct, as far as I can tell.

    The reference COULD be null there, depending on the implementation of GetClassB(). So, technically, there could be a null-reference waiting to happen there.

    However, if the contents of GetClassB() looks like this:

    return gcnew ClassB();
    

    you are guaranteed to either throw an exception or succeed, which means that the reference would never accidentally be null.

    So, the real answer is: It depends, but you are never required to check for null.

    To check for null use:

    if (b == nullptr)
    {
    }