Returning a local object from a function
Solution 1
getCar
returns a Car
by value, which is correct.
You cannot pass that return value, which is a temporary object, into displayCar
, because displayCar
takes a Car&
. You cannot bind a temporary to a non-const reference. You should change displayCar
to take a const reference:
void displayCar(const Car& car) { }
Or, you can store the temporary in a local variable:
Car c = getCar("Honda", 1999);
displayCar(c);
But, it's better to have displayCar
take a const reference since it doesn't modify the object.
Do not return a reference to the local Car
variable.
Solution 2
It is not safe to return a local variable's reference from a function.
So yes this is correct:
Car getCar(string model, int year) {
Car c(model, year);
return c;
}
Solution 3
Yes, it is definitely not safe to return a reference or a pointer to a temporary object. When it expires (ie, when the function getCar
exits), you'll left with what is technical known as a "dangling pointer".
However, if you're keen on reducing copy operations on an object, you should check out C++0x's "Move semantics". It is a relatively new concept, but I'm sure it'll become main-stream soon enough. GCC 4.4 upwards supports C++0x (use the compiler option -std=c++0x
to enable).
pocoa
Updated on June 25, 2022Comments
-
pocoa almost 2 years
Is this the right way to return an object from a function?
Car getCar(string model, int year) { Car c(model, year); return c; } void displayCar(Car &car) { cout << car.getModel() << ", " << car.getYear() << endl; } displayCar(getCar("Honda", 1999));
I'm getting an error, "taking address of temporary". Should I use this way:
Car &getCar(string model, int year) { Car c(model, year); return c; }