2016-11-23 92 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.