In C++, if a class has a reference data member the default assignment operator is not synthesized by compiler. Why?
In C++, if a class has a reference data member the default assignment operator is not synthesized by compiler. Why?
What an copy assignment should do is defined in:
C++03 Standard 12.8/13:
Each subobject is assigned in the manner appropriate to its type:
if the subobject is of class type, the copy assignment operator for the class is used (as if by explicit qualification; that is, ignoring any possible virtual overriding functions in more derived classes);
if the subobject is an array, each element is assigned, in the manner appropriate to the element type;
if the subobject is of scalar type, the built-in assignment operator is used.
In short It implies that each of the member should assigned in an appropriate manner
which raises the question,
What should be the behavior for assignment of a reference member in class?
Consider the following about references:
#1
assigning to an reference doesn't reassign the reference, it changes the value of the referrant which is non-intuitive behavior.There is no default correct behavior to be enforced here but a rather situational one.So the C++ Standard mandates that designer of the class is in best position to determine this behavior and hence the decision that default assignment operator should not be synthesized by compiler if a class has a reference data member.
This decision is specified in:
C++03 Standard 12.8/12:
An implicitly-declared copy assignment operator is implicitly defined when an object of its class type is assigned a value of its class type or a value of a class type derived from its class type. A program is ill formed if the class for which a copy assignment operator is implicitly defined has:
.......
— a nonstatic data member of reference type, or
.......
[Ref 1]
C++03 Standard 8.5.3/2:
A reference cannot be changed to refer to another object after initialization. Note that initialization of a reference is treated very differently from assignment to it. Argument passing (5.2.2) and function value return (6.6.3) are initializations.
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