在 C++/CLI 项目中,我在 native C++ 类中有一个方法,我想检查 NULL
或 nullptr的
。我该怎么做呢?以下似乎都不起作用:gcroot
引用
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_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;
}
结果:
aString == nullptr aString != nullptr
关于c++ - 如何测试 NULL 或 nullptr 的 gcroot 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21239090/