Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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

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

int main(int argc, char** argv)
{
    int x = 23;

    A a1(x);   // why this line is fine?

    A a2 = a1; // why this line is fine?

    a2 = a1; // error: use of deleted function 'A& A::operator=(const A&)'
            // note: 'A& A::operator=(const A&)' is implicitly deleted because the default definition would be ill-formed:
            // error: non-static reference member 'int& A::r', can't use default assignment operator
    return 0;
}

The default assignment operator is deleted. Why the default copy constructor is still kept?

like image 553
q0987 Avatar asked Mar 13 '17 01:03

q0987


People also ask

Why copy constructor take reference variable as argument?

A copy constructor defines what copying means,So if we pass an object only (we will be passing the copy of that object) but to create the copy we will need a copy constructor, Hence it leads to infinite recursion. So, A copy constructor must have a reference as an argument.

Why reference is used in copy constructor in C++?

When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified.

What does the default copy constructor do?

Default Copy Constructor This is called a default or standard copy constructor. What it does is simply copy data members of the object passed to it to the corresponding data members of the new object.

Are references copied in C++?

C++ gives you the choice: use the assignment operator to copy the value (copy/value semantics), or use a pointer-copy to copy a pointer (reference semantics). C++ allows you to override the assignment operator to do anything your heart desires, however the default (and most common) choice is to copy the value.


1 Answers

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.

like image 142
AndyG Avatar answered Oct 28 '22 05:10

AndyG