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

1

19

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.

Ehling answered 24/6, 2010 at 13:14 Comment(3)
Have you tried using the nullptr keyword? It's a C++/CLI keyword, but maybe it works also with Managed C++. msdn.microsoft.com/en-us/library/4ex65770.aspxChaunce
@DanDan: he's talking about .NET references, not C++ ones.Bushwhacker
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.Lindsay
P
28

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)
{
}
Palaeontology answered 24/6, 2010 at 13:16 Comment(2)
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.Ehling
yes, what I forgot is, the exceptions could be thrown by ClassB here anyway, which I can't prevent :)Ehling

© 2022 - 2024 — McMap. All rights reserved.