why default copy-ctor is generated for a class with reference member variable?

后端 未结 3 1379
予麋鹿
予麋鹿 2021-01-05 02:41

http://coliru.stacked-crooked.com/a/8356f09dff0c9308

#include 
struct A
{
  A(int& var) : r(var) {}
  int &r;
};

int main(int argc,          


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-05 03:13

    A a1(x);
    

    is fine because it's constructing an instance of A with a reference (x is turned into a reference and the constructor A(int&) is called)

    A a2 = a1;
    

    Is also fine because it is still construction. Copy construction, in fact. It's okay to initialize a reference with another reference.

    For instance:

    int a = 1;
    int& b = a;
    int& c = b;
    

    Is okay because this is all construction (Demo)

    However, you cannot assign a reference, which is what a2 = a1 will attempt to do through a compiler-generated copy-assignment operator. However, the compiler recognized this and did not generate such an operator. Since the operator does not exist, you got a compiler error.

提交回复
热议问题