如何测试NULL或NULLPTR的GCROOT参考
How to test gcroot reference for NULL or nullptr?
在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)
}
}
编辑
以上只是一个简化的示例。我实际上正在研究一个包装库,该图书馆在托管和本机代码之间"翻译"。我正在研究的类是包裹托管对象的本机C 类。在本机C 类的构造函数中,我获得了我想检查null的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;
}
结果:
挤压== nullptr夸耀!= nullptr
这也有效:
void Foo::doIt(gcroot<System::String^> aString)
{
if (System::Object::ReferenceEquals(aString, nullptr))
{
System::Diagnostics::Debug::WriteLine("aString == nullptr");
}
}
这是另一个技巧,可能更可读性:
void PrintString(gcroot <System::String^> str)
{
if (str.operator ->() != nullptr)
{
Console::WriteLine("The string is: " + str);
}
}
相关文章:
- 如何在自删除后将对象设置为nullptr
- 如何取消对nullptr的屏蔽,返回正确的对象
- C++ - "!pointer"和"pointer == nullptr"的区别?
- 将指针设置为"nullptr"并不能防止双重删除?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 为什么我的节点在我设置后被设置为 nullptr = 新节点?
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 哈希映射使用 nullptr c++ 初始化节点的动态数组
- wx通用目录控制错误"wxTheFileIconsTable was nullptr"
- 当设置为 const 变量时使用 nullptr
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- 检查类方法中是否(此 == nullptr)
- C++98,但叮叮当当地说使用nullptr?
- 为什么调试器引发"read access violation. this was nullptr"异常?
- 检查模板中 nullptr 的函数指针,了解任何类型的可调用对象
- 检查nullptr是否100%保护内存布局不受segfault影响
- 向unordered_map添加unique_ptr时'this was nullptr'
- 如何测试NULL或NULLPTR的GCROOT参考