Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a default assignment operator not synthesis by compiler if a class has a reference data member

Tags:

c++

In C++, if a class has a reference data member the default assignment operator is not synthesized by compiler. Why?

like image 222
minghua Avatar asked May 28 '12 07:05

minghua


1 Answers

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. References are inherently non assignable, they keep referring the same referrant to which they were initialized[Ref 1].
  2. By virtue of #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.

like image 133
Alok Save Avatar answered Sep 19 '22 17:09

Alok Save