2013-03-17 92 views
3

當然,我想不出任何理由爲什麼我會永遠覆蓋一元&運營商,但在https://stackoverflow.com/a/4542813/368896海報狀態,在關於某些類X爲什麼「愚蠢的覆蓋&運算符並返回* this *」?

...除非X不一些非常愚蠢的,像超載一元& 回到這個

(注:我認爲這個評論是指&操作的事實返回this,而不是。事實上重寫&運營商本身)

,因爲我以爲有關評論,它發生,我認爲「迴歸這」 正是&運營商做什麼 - 即使是在多重繼承的情況下。

考慮到一個可能永遠不會覆蓋一元&運營商,不過它爲什麼會成爲啞巴使其返回this(如果你沒有決定重寫它)?

回答

7

它發生,我認爲「迴歸這」正是&符不

你是對的,雖然C++還不允許取一個臨時對象的地址

the question you reference的背景下,這是有關確定對象是否是暫時的:

如果您實現自己的operator &返回this,你會告訴編譯器&(expression)總是有效的繞過這種保護。考慮:

struct foo 
{ 
}; 

struct bar 
{ 
    bar* operator&() 
    { 
     return this; 
    } 
}; 

template <typename T> 
void test(const T*) 
{ 
    // no temporaries, can't take address of temporary...right? 
} 

int main() 
{ 
    foo x; 
    test(&x); // okay, x is an lvalue 

    /* 
    test(&(foo())); // not okay, cannot take address of temporary 
    */ 

    bar y; 
    test(&y); // still okay, y is an lvalue 

    test(&(bar())); // huh?! not taking address of temporary, calling operator& 
} 
+0

你打敗了我,所以我添加了我寫的示例代碼。按你喜歡的方式編輯。 – GManNickG 2013-03-17 19:00:29

+0

@GManNickG感謝您的協助。在我看來很好。 :) – 2013-03-17 19:01:01

2

它確實具有非常有限的用途。 例如,一個用例是智能點,因爲它們通常用於Direct3D中以包裝IUnknown對象。

我假設你不熟悉Direct3D,所以我會再談一談。 許多Direct3D類從IUnknown派生,並且在使用它們之後,必須調用Release。是的,D3D內部使用引用計數。人們往往忘記撥打Release,這真的很乏味。因此,將IUnknown封裝到smartpointer中,該功能將在幕後發佈。

smart_pointer<ID3D11Device> device = // .. 

因此,通過陳述&device你不想要的smart_pointer<ID3D11Device>的地址,你要的ID3D11Device地址。

template <class T> 
class com_ptr 
{ 
private: 
    T *inst; 

public: 
    // many other methods/overloadings 

    T** operator &() 
    { 
     return &inst; 
    } 
}; 

底線:這樣,您就可以調用析構函數Release並沒有去關心它的代碼的其餘部分。

底線2:更好的方法是添加一個返回實體對象的方法get()

T** get() 
    { 
     return &inst; 
    } 
+0

我不明白如何使用智能指針需要重載'operator&'。 – GManNickG 2013-03-17 18:54:43

+0

是的,我們可以得到許多使用智能指針的例子:boost,QuantLib即,但請參考接近超載& – 4pie0 2013-03-17 18:55:32

+0

@ cf16,@ GManNickG增加了一個例子 – poitroae 2013-03-17 18:57:33