如何测试NULL或nullptr的gcroot引用?

her*_*ube 16 c++ c++-cli nullpointerexception

在C++/CLI项目中,我在本机C++类中有一个方法,我想检查or 的gcroot引用.我该怎么做呢?以下所有内容似乎都不起作用:NULLnullptr

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

以上只是一个简化的例子.我实际上正在开发一个在托管代码和本机代码之间"翻译"的包装器库.我正在处理的类是一个包装托管对象的本机C++类.在本机C++类的构造函数中,我得到一个gcroot我想要检查null 的引用.

Dav*_*Yaw 25

使用a static_cast将转换gcroot为托管类型,然后将其进行比较nullptr.

我的测试程序:

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;
}
Run Code Online (Sandbox Code Playgroud)

结果:

aString == nullptr
aString != nullptr


her*_*ube 13

这也有效:

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


Evg*_*tov 5

这是另一个技巧,可能更具可读性:

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