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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With