[英]Overloaded == and comparison with nullptr?
我正在編寫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;
}
行if(instance == nullptr)調用我的==運算符的重載實現。
static bool operator==(MyWrapper^ a, MyWrapper^ b)
{
return a->InternalInstance == b->InternalInstance; //Here System.AccessViolationException Exception
}
問題是如果a為null,則會拋出System.AccessViolationException異常。
我不能簡單地為a和b添加與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;
}
如何覆蓋==運算符以使用我的C ++ Native實現,並且仍然保護我的句柄為空?
使用Object::ReferenceEquals
顯式檢查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;
}
這里的問題是重載函數o == operation是在C ++ / CLI中對引用類型執行的,所以如果我們按照相同的方式在本機C ++中執行此操作,則意味着執行==運算符的重載函數指針類型。 但在本機C ++中,我們通常定義==運算符,如下所示:
bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
或者這樣想,如果你在本機C ++中重載指針類型的==,你如何將這個類指針與null進行比較?
在托管環境中,默認情況下,運算符==通過確定兩個引用是否指示同一對象來測試引用相等性,因此引用類型不需要實現operator ==以獲得此功能。 所以你應該實現Equals函數而不是重載==
請參考: 重載等於()和運算符==的指南 。 雖然它是關於C#的,但我認為它也適用於C ++ / CLI中的托管類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.