2016-11-23 48 views
0
class B 
{ 
public: 
    B(int& a) :ref(a){} 
    B(B const&) = default; 
    int& ref; 
}; 


void main() 
{ 
    int a1 = 1, a2 = 2; 
    B b1(a1), b2(b1), b3(a2); 
    b3 = b1; 

} 

如果編譯器執行的隱式定義的拷貝賦值運算符是,隱式定義的拷貝賦值運算符

B& operator=(const B& rhs) 
{ 
    this->ref = rhs.ref; 
    return *this; 
} 

爲什麼不能引用生成?綁定到變量a的初始別名不受影響,因爲在複製賦值運算符中,引用變量ref的數值會被更改。

+3

http://stackoverflow.com/questions/26946201/why-do-reference-type-members-cause-implicitly-declared-copy-assignment-operator的DUP? –

+2

'main'必須返回'int',而不是'void'。 – melpomene

回答

1

它可以做到這一點,因爲引用不能被反彈到另一個。

如果像你所提供的編譯器會生成一個功能,我這樣做:

struct Ref { 
    int& num; 
    // hypotetical operator= generated 
}; 

// ... 

int a = 2; 
int b = 5; 

Ref ra{a}; 
Ref rb{b}; 

ra = rb; // now a = 5. Quite confusing. 

a = 3; // still changes what value `ra.num` yeild. rb is not affected. 

// will print "false". 
std::cout << std::boolalpha << (ra.num == rb.num) << std::endl; 

這會導致一些嚴重錯誤。

我對這個問題的首選解決方案是不在乎。我認爲operator=對絕大多數用例來說都不是絕對需要的。

但是,如果你真的想提供一個operator=到類的用戶,可以容納一個指針或std::reference_wrapper而不是一個參考。兩者都可以讓你的課程成爲可分配的,從而使你的引用可重新引用。在這兩者之間,我通常更喜歡指針,因爲在我看來,它們更直接。

struct Ref { 
    std::reference_wrapper<int> num; 
}; 

// -- or -- 

struct Ref { 
    Ref(int& ref) : num{&ref} {} 

    int* num; 
}; 

// ... 

int a = 2; 
int b = 5; 

Ref ra{a}; 
Ref rb{b}; 

ra = rb; // now ra.num and rb.num are bound to the same reference. 
相關問題