重载==并与nullptr进行比较?

Dzy*_*ann 3 c++ c++-cli

我正在编写C++ Native Static Library的C++/CLI包装器.

我对C++/CLI或C++没有多少经验.我已经按照我在互联网上阅读的最佳实践来创建C++/CLI包装器.我的包装器有一个指向C++类的指针.我的C++有运算符==重载.

我试图在我的包装器中重载它并使用C++类的实现,但是当包装器为null时我遇到错误.

我搜索了如何知道我的句柄是否为空,我发现你必须将它与nullptr进行比较.

我在C++/CLI中有这个方法

       MyOtherClass const* MyClass::MyMethod(MyWrapper^ instance)   
    {
        if(instance == nullptr)
        {
           return NULL;
        }

        return instance->Property;      
    }
Run Code Online (Sandbox Code Playgroud)

if(instance == nullptr)调用我的==运算符的重载实现.

      static bool operator==(MyWrapper^ a, MyWrapper^ b)
    {
        return a->InternalInstance == b->InternalInstance; //Here System.AccessViolationException Exception
    }
Run Code Online (Sandbox Code Playgroud)

问题是如果a为null,则会抛出System.AccessViolationException异常.

我不能简单地为ab添加与nullptr的比较,因为它会创建堆栈溢出.

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;
}
Run Code Online (Sandbox Code Playgroud)

如何覆盖==运算符以使用我的C++ Native实现,并且仍然保护我的句柄为空?

Dav*_*Yaw 7

使用Object::ReferenceEquals明确检查空.

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我知道,但我认为在调用静态方法时指定类名通常是一种好习惯. (4认同)