Afficher un message
Vieux 18/10/2007, 07h44   #2
Kai-Uwe Bux
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Overloaded assignment operator

Bruno Panetta wrote:

> I am going through Deitel & Deitel's C++ book (section 8.8 of the
> fourth edition), in which they construct an Array class and show how
> to overload operators. The assignment operator is overloaded as
> follows:
>
> const Array &operator=(const Array &);
>
> According to D&D, the const return is designed to avoid (a1 = a2) =
> a3. My questions are:
>
> 1) Why is this necessary? After all, an assignment like (a1 = a2) = a3
> works for ordinary variables.


It is not necessary. It's a design decision, and a debatable one. Note that
the standard describes the Assignable requirement in Table 64 as follows:
the expression t=u has to have the postcondition that t be equivalent to u
and the return type T&. It follows that classes whose assignment operator
returns a const reference are not assignable. Consequently, something like

std::vector< Array >

is not required to compile. (Although in practice, only the most zealous
concept checking libraries will snap at that.)


Also note that the standard containers all have an assignment operator that
return a non-const reference (in fact, this is a container requirement). I
don't see a good reason to depart from this pattern.


> 2) What if you want to use this method on a non-constant Array object,


No problem.

> or if you want it to return a non-constant Array?


Then you should make the return type non-const.

> I can see it still works, but why don't the const declarations get in the
> way?


Huh?

Please provide a piece of code that illustrates your worries.


Best

Kai-Uwe Bux
  Réponse avec citation
 
Page generated in 0,08580 seconds with 9 queries