17

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.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Echo
  • 173
  • 1
  • 1
  • 4
  • 1
    Have you tried using the `nullptr` keyword? It's a C++/CLI keyword, but maybe it works also with Managed C++. http://msdn.microsoft.com/en-us/library/4ex65770.aspx – dtb Jun 24 '10 at 13:17
  • @DanDan: he's talking about .NET references, not C++ ones. – jalf Jun 24 '10 at 13:35
  • What kind of odd mix of Managed Extensions for C++ and C++/CLI is this? C++/CLI doesn't have the `__gc` keyword, MEC++ doesn't have the `gcnew` keyword, and `public:` isn't capitalized in any flavor of C++ I've ever seen. – Ben Voigt Sep 22 '10 at 05:54

1 Answers1

27

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)
{
}
John Gietzen
  • 48,783
  • 32
  • 145
  • 190
  • Thanks so much for your quick answer :) The reason why I want to check NULL is that I didn't write both classes. They're included in .NET library. Since I can't tell what will really be returned if error happens, and don't want to throw exceptions "too frequently" at run time, so I would rather do the simple check at this point. :) E. – Echo Jun 24 '10 at 13:38
  • yes, what I forgot is, the exceptions could be thrown by ClassB here anyway, which I can't prevent :) – Echo Jun 24 '10 at 13:51