I am writing a C++/CLI wrapper of a C++ Native Static Library.
I don't have much experience with either C++/CLI or C++. I have followed best practices I read on internet for the creation of C++/CLI wrappers. My wrapper has a pointer to the C++ class. And my C++ has the operator == overloaded.
I am trying to overload it also in my wrapper and use the implementation of the C++ class, but I am getting errors when the wrapper is null.
I searched how to know if my handle is null, and I found that you have to compare it with nullptr.
I have this method in C++/CLI
MyOtherClass const* MyClass::MyMethod(MyWrapper^ instance)
{
if(instance == nullptr)
{
return NULL;
}
return instance->Property;
}
The line if(instance == nullptr) calls my overloaded implementation of the == operator.
static bool operator==(MyWrapper^ a, MyWrapper^ b)
{
return a->InternalInstance == b->InternalInstance; //Here System.AccessViolationException Exception
}
The problem is that if a is null, this will throw an System.AccessViolationException exception.
And I cant just simply add a comparison with nullptr for a and b, because It creates a stack overflow.
static bool operator==(MyWrapper^ a, MyWrapper^ b)
{
if(a == nullptr && b == nullptr) //Stack Overflow here because a == nullptr calls this method again.
return true;
if((a == nullptr && b != nullptr) || (a != nullptr && b == nullptr))
return false;
return a->InternalInstance == b->InternalInstance;
}
How can I override the == operator to use my C++ Native implementation, and still be protected of my handle being null?
bool()operator that returns true ifMyWrapper ^is not a null ptr - yizzlezif (a && b && a->InternalInstance == b->InternalInstance)should do it. If eitheraorbisNULL, it would evaluate tofalse, so the other conditionals would never get executed. - Zac HowlandNULLornullptr, it should equate tofalseif you had a statementif (a). The other option is to useReferenceEquals. - Zac Howland