By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,778 Members | 1,919 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,778 IT Pros & Developers. It's quick & easy.

operator= Q.

P: n/a
Meyers says to return a reference to *this, but can you also return a copy
of *this? Is the reference for efficiency?
Dec 19 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
"vsgdp" <sp**@void.com> wrote in message
news:despf.276$LB5.26@fed1read04...
: Meyers says to return a reference to *this, but can you also return a
copy
: of *this? Is the reference for efficiency?

The reference is for consistency with the behavior of built-in
and standard types. Under some uses / template code, returning
a different instance from op= will cause problems.
Why would you want to return a copy of *this ?

Cheers,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com


Dec 19 '05 #2

P: n/a

vsgdp wrote:
Meyers says to return a reference to *this, but can you also return a copy
of *this? Is the reference for efficiency?


Returning a (non-const) reference allows you to treat the result of
assignment as l-value
Eg : (a=b).foo().
This is not possible if operator=() returns a value.

Also, the "returning by reference" has nothing to do with the actual
behaviour of "assignment" as such. But if you return void from
operator=(), you will not be able to chain assignments

Eg : a = b = c =d ; // needs operator=() return a non-void

Returning by value will add an overhead due to unnecessary calls to
copy constructors.

Dec 19 '05 #3

P: n/a
Neelesh Bodas wrote:
vsgdp wrote:
Meyers says to return a reference to *this, but can you also return a copy
of *this? Is the reference for efficiency?
Returning a (non-const) reference allows you to treat the result of
assignment as l-value


This is true, but your example below does not illustrate that.
Eg : (a=b).foo().
This is not possible if operator=() returns a value.


This _is_ perfectly possible with a non-lvalue result. The left-hand side of
member selection operator ('.') is not required to be lvalue.

--
Best regards,
Andrey Tarasevich
Dec 19 '05 #4

P: n/a

Andrey Tarasevich wrote:
This is true, but your example below does not illustrate that.
Eg : (a=b).foo().
This is not possible if operator=() returns a value.


This _is_ perfectly possible with a non-lvalue result. The left-hand side of
member selection operator ('.') is not required to be lvalue.

Point taken. Thanks.

Dec 19 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.