在C++/CLI项目中,我在本地C++类中有一个方法,我想在gcroot
引用中检查NULL
或nullptr
。我该怎么做呢?以下内容似乎都不起作用:
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
引用,我想检查该参数是否为null。 最佳答案
使用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