Re: What to return -- object, reference or const reference
In message
<864976eb-2df5-4427-9554-22e137b08fd3@34g2000hsz.googlegroups.com>,
EventHelix.com <eventhelix@gmail.com> writes
[...]
In C++ returning an object is suitable only when the object contains
only a few data members. Returning an object results in a copy of
entire object thus it can have really impact performance if objects
with a large list of data members is returned.
You're recommending premature optimisation, which is never a good idea.
If _measurement_ indicates that this copy has an impact on performance,
_then_ consider an alternative.
Note that in an object return, the copy constructor gets called (if
defined). If the copy constructor is not defined, an exact copy of the
object is returned.
Not "exact", memberwise, which does whatever the members' copy
constructors say it does.
An object copy can result in hard to debug memory allocation issues.
Consider the case where the object being copied contained pointers to
dynamically allocated memory.
Then you should have either defined an appropriate copy constructor (and
probably a copy assigment operator and destructor), or disabled copying.
Don't blame the user if you provide him with a fundamentally broken
class.
Only the pointers would be copied. Thus
both objects would be pointing to the same allocated memory.
Return by reference can result in hard to debug pointer issues.
Consider the case where instead of a copy, you return a dangling
reference to a local variable which has gone out of scope and been
deleted. Thus the non-reference refers to a non-object which is
not-pointing to some not-allocated memory. If you'd only returned a
properly-constructed copy, none of this would have happened.
--
Richard Herring