Overloaded == and comparison with nullptr?
c++, c++-cli
Solution
Use `Object::ReferenceEquals` to explicitly check for null.
static bool operator==(MyWrapper^ a, MyWrapper^ b)
{
if(Object::ReferenceEquals(a, nullptr) && Object::ReferenceEquals(b, nullptr))
return true;
if(Object::ReferenceEquals(a, nullptr) || Object::ReferenceEquals(b, nullptr))
return false;
return a->InternalInstance == b->InternalInstance;
}
Problem
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?