What I've understood, the reason is that we unnecessarily call the copy constructor for a simple statement like a=b;
(both are objects).
What I don't get is that in my book it's written that we should never pass an object by reference, because as soon as the function terminates, that reference ceases to exist.
So is the text written in my book wrong or am I missing something here? Text ref: Overloading assignment operator in C++
There's nothing wrong with returning a reference from a function.
Indeed that's how the assignment operator operator=
is normally defined (with return *this;
for method chaining)!
What you shouldn't do is return a reference to an object that goes out of scope, e.g.
int& undefinedBehaviourServer()
{
int ub;
return ub;
}
In this case, ub
has automatic storage duration and the returned reference to it will dangle.