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

标签 c++ nullpointerexception c++-cli

在 C++/CLI 项目中,我在 native C++ 类中有一个方法,我想检查 NULLnullptrgcroot 引用。我该怎么做呢?以下似乎都不起作用:

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)
    }
}

编辑

以上只是一个简化的例子。我实际上正在开发一个在托管代码和 native 代码之间“转换”的包装库。我正在研究的类是包装托管对象的 native C++ 类。在 native C++ 类的构造函数中,我得到一个 gcroot 引用,我想检查它是否为空。

最佳答案

使用 static_castgcroot 转换为托管类型,然后将其与 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;
}

结果:

aString == nullptr
aString != nullptr

关于c++ - 如何测试 NULL 或 nullptr 的 gcroot 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21239090/

相关文章:

c++ - 解压模板模板函数的可变参数?

java - Android Intent 按钮 NullPointerException

java - 执行 parallelStream.forEach(..) 时 native java 代码中的 NullPointerException

.net - 定义具有相同名称和不同数量类型参数的泛型类 (C++/CLI)

.net - 新的 .NET 2.0 C++/CLI 项目对 mscorlib v4 有隐式依赖吗?

c++ - 调用堆栈(到底)在哪里?

c++ - 共享指针上的原子操作,C++ 版本

java - 什么是NullPointerException,我该如何解决?

windows - 如何制作 System::Windows::Forms::Checkbox^ 的向量/数组

c++ - MinGW 链接单个 EXE