views:

89

answers:

3
iarray<T>& operator =    (iarray<T>& v)

Why the return type is iarray<T>& not iarray<T> ?

UPDATE

Can someone elaborate in great detail why iarray<T> const &v ?

+8  A: 

Because you don't want to return a copy of the array just for the sake of chaining. Returning a reference is a better option as it doesn't result in a copy being constructed.

OJ
Right, should have said "efficiently", corrected.
Charlie Martin
+3  A: 

Because then you can chain them efficiently, eg.

a = b = c;

See the C++ FAQ.

Charlie Martin
A: 

Why the return type is iarray& not iarray ?

Because the result of an assignment is a reference to what just got assigned. For example, the result of a = b should be a reference to a so you can chain them together like in c = a = b; which is effectively a = b; c = a;. (Yes, people like doing this on rare occasions; no, I don't know why it's such a hardship to break it into two lines.) Thus your code should look like:

iarray<T>& iarray<T>::operator = (const iarray<T>& v)
{
   // ... copy `v`'s state over this object's ...

   return *this;
}

Can someone elaborate in great detail why iarray const &v ?

Because an assignment operation has no business changing the right-hand side; it is unexpected behavior. If you have some funky thing in your object that needs to change, like a reference count, then you should prefer declaring that one part mutable over disallowing const right-hand side expressions. You can pass a non-const value in for a const parameter, but the reverse is not true.

Mike DeSimone
I think chaining also works if the return type is `iarray<T>`,dont you?
Alan
It results in the creation and destruction of an unnecessary temporary object. So return a reference. Make it a `const` reference if it makes you feel better.
Mike DeSimone