Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has anyone found the need to declare the return parameter of a copy assignment operator const?

The copy assignment operator has the usual signature:

    my_class & operator = (my_class const & rhs);

Does the following signature have any practical use?

    my_class const & operator = (my_class const & rhs);

You can only define one or the other, but not both.

like image 295
Keith M Smith Avatar asked Apr 15 '10 21:04

Keith M Smith


2 Answers

The principle reason to make the return type of copy-assignment a non-const reference is that it is a requirement for "Assignable" in the standard.

If you make the return type a const reference then your class won't meet the requirements for use in any of the standard library containers.

like image 158
CB Bailey Avatar answered Sep 28 '22 05:09

CB Bailey


Don't do that. It prevent a client from writing something like:

(a = b).non_const_method();

instead of the longer form:

a = b;
a.non_const_method();

While you may not like the shorthand style, it's really up to the user of the library to decide how they want to write the code.

like image 21
R Samuel Klatchko Avatar answered Sep 28 '22 07:09

R Samuel Klatchko