Re: What to return -- object, reference or const reference
On Mar 6, 12:16 pm, "EventHelix.com" <eventhe...@gmail.com> wrote:
On Mar 6, 4:10 am, Arv <arvind.b...@gmail.com> wrote:
After writing code in Java for sometime, one thing that I am not
comfortable at all with C++ is the return type of an object.
In java, i do not remember ever seeing a method return a final
reference -- though a const is not equivalent to final, it is
confusing when i see some methods returning a const reference.
I initially assumed returning an object is same as returning a
reference, because when i call the method as
Myclass O1;
O1 = func();
Does it matter if func() returns a reference, const reference or a
Object, anyways the assignment operator is going to get called.
But I am a bit confused when I call AnotherFunc(func())... so is it
possible that if I dont pass a const reference, and the AnotherFunc
accepts a reference, it can potentially change the object I pass.!
Especially this is more confusing in a getter method, should a getter
return a const reference always, because I do not want ppl to modify
the reference they get by calling a getter.
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.
That's bullshit. Return by reference results in different
semantics than return by value, and you can't simply replace one
with the other. The default return type in C++ is by value
(just as the default behavior everywhere is by value). If you
have a performance problem, and the profiler shows it to be due
to excess copies, then most of the time, the solution is to use
an out parameter, rather than return by reference.
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.
If no accessible copy constructor is defined, you can't copy,
period. If no user-defined copy constructor is declared, the
copy is member by member, not "exact" (whatever that means---I
would assume bitwise).
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. Only the
pointers would be copied. Thus both objects would be pointing
to the same allocated memory.
Not providing a copy constructor when one is needed will cause a
number of problems. Regardless of whether you return by value
or return by reference. One of the very first things one learns
in C++ is to either ensure that the copy constructor works
correctly, or that copy is inhibited.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34