Как проверить ссылку gcroot для NULL или nullptr?
В проекте С++/CLI у меня есть метод в собственном классе С++, где я хотел бы проверить ссылку 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)
}
}
ИЗМЕНИТЬ
Вышеприведенный пример является просто упрощенным. Я фактически работаю над библиотекой-оберткой, которая "переводит" между управляемым и собственным кодом. Класс, над которым я работаю, является родным классом С++, который обертывает управляемый объект. В конструкторе родного класса С++ я получаю ссылку gcroot
, которую я хочу проверить для null.
Ответы
Ответ 1
Используйте 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
Ответ 2
Это также работает:
void Foo::doIt(gcroot<System::String^> aString)
{
if (System::Object::ReferenceEquals(aString, nullptr))
{
System::Diagnostics::Debug::WriteLine("aString == nullptr");
}
}
Ответ 3
Вот еще один трюк, может быть еще более читабельным:
void PrintString(gcroot <System::String^> str)
{
if (str.operator ->() != nullptr)
{
Console::WriteLine("The string is: " + str);
}
}