I remember reading somewhere that we should avoid returning objects that are created locally within the called function (i.e. only dynamically allocated objects may be returned). However, I am not sure if that is sound advice because when dealing, for example, with overloaded operators we may have code like the following (taken from Object-Oriented Programming in C by Lafore, 4e) :
//
Distance operator (Distance d1, Distance d2) //add d1 to d2
{
int f = d1.feet d2.feet; //add the feet
float i = d1.inches d2.inches; //add the inches
if(i >= 12.0) //if inches exceeds 12.0,
{ i -= 12.0; f ; } //less 12 inches, plus 1 foot
return Distance(f,i); //return new Distance with sum
}
//--------------------------------------------------------------
Question: What are the dos and don'ts for returning automatically allocated objects from a function?
CodePudding user response:
I remember reading somewhere that we should avoid returning objects that are created locally within the called function (i.e. only dynamically allocated objects may be returned).
You remember wrong.
You should not return pointers or references to local objects:
int& foo() {
int x = 42;
return x; // DONT DO THIS
}
The returned reference is dangling. It refers to an int
whose lifetime ended when the function returned. The function itself is kind of "ok", but the caller cannot read from the returned reference without invoking undefined behavior.
There is no problem with returning a copy of a local variable, other than a copy that you maybe can avoid, but that doesn't apply to operator
. Also there is RVO and copy elision (see What are copy elision and return value optimization?). In the code you posted the operator should take its parameters by const&
to avoid a copy, but you cannot avoid creating a new instance, because the result needs to be stored somewhere.