herzbube
herzbube

Reputation: 13378

How to test gcroot reference for NULL or nullptr?

In a C++/CLI project I have a method in a native C++ class where I would like to check a gcroot reference for NULL or nullptr. How do I do this? None of the following seems to work:

void Foo::doIt(gcroot<System::String^> aString)
{
    // This seems straightforward, but does not work
    if (aString == nullptr)
    {
        // compiler error C2088: '==': illegal for struct
    }

    // Worth a try, but does not work either
    if (aString == NULL)
    {
        // compiler error C2678: binary '==' : no operator found
        // which takes a left-hand operand of type 'gcroot<T>'
        // (or there is no acceptable conversion)
    }


    // Desperate, but same result as above
    if (aString == gcroot<System::String^>(nullptr))
    {
        // compiler error C2678: binary '==' : no operator found
        // which takes a left-hand operand of type 'gcroot<T>'
        // (or there is no acceptable conversion)
    }
}

EDIT

The above is just a simplified example. I am actually working on a wrapper library that "translates" between managed and native code. The class I am working on is a native C++ class that wraps a managed object. In the constructor of the native C++ class I get a gcroot reference which I want to check for null.

Upvotes: 20

Views: 12171

Answers (4)

Mubarrat Hasan
Mubarrat Hasan

Reputation: 304

You can also use casting to do it. Because gcroot<T> defined casting operator. Like this:

void Foo::doIt(gcroot<System::String^> aString)
{
    if ((System::String^)aString == nullptr)
    {
        // Since you casted to `System::String^`, and
        // `System::Object^` supports comparing. It'll work.
    }
}

Upvotes: 1

jenkas
jenkas

Reputation: 971

Here is another trick, may be even more readable:

void PrintString(gcroot <System::String^> str)
{
    if (str.operator ->() != nullptr)
    {
        Console::WriteLine("The string is: " + str);
    }
}

Upvotes: 6

herzbube
herzbube

Reputation: 13378

This also works:

void Foo::doIt(gcroot<System::String^> aString)
{
    if (System::Object::ReferenceEquals(aString, nullptr))
    {
        System::Diagnostics::Debug::WriteLine("aString == nullptr");
    }
}

Upvotes: 17

David Yaw
David Yaw

Reputation: 27874

Use a static_cast to convert the gcroot to the managed type, and then compare that to nullptr.

My test program:

int main(array<System::String ^> ^args)
{
    gcroot<System::String^> aString;

    if (static_cast<String^>(aString) == nullptr)
    {
        Debug::WriteLine("aString == nullptr");
    }

    aString = "foo";

    if (static_cast<String^>(aString) != nullptr)
    {
        Debug::WriteLine("aString != nullptr");
    }

    return 0;
}

Results:

aString == nullptr
aString != nullptr

Upvotes: 29

Related Questions