In Java, where all classes are really references, I do this:
Car getCar(int mileage)
{
Car car = new Car();
car.setMileage(mileage);
return car;
}
In C++, how do I do this? I can put it into a reference:
void getCar(int mileage, Car& car)
{
car.setMileage(mileage);
return true;
}
Or, I can create a new object:
Car* getCar(int mileage)
{
Car* car = new Car;
car.setMileage(mileage);
return car;
}
But then, the caller is also responsible for deleting car.
I don’t want to return a pointer. I want to return a Car:
Car getCar(int mileage)
{
Car car;
car.setMileage(mileage);
return car;
}
But of course, car is a local variable which will be deleted once the function finishes.
What’s generally the ‘standard’ way of doing this? Which is the best way, and why?
Your final example is the correct and idiomatic way to return an object:
Yes,
carwill be deleted at the end of the function, but not before it is copied into the returned object. You might invoke this function like so:The
carthat is local togetCaris copied into the calling environment’smyCar.What you can’t and must not do is to return a reference to or a pointer to a local variable.
This is WRONG:
This is also WRONG:
In each of these cases, you are allowing the calling function access to an object which no longer exists.
You mustn’t return a pointer or reference to a local. You may return a copy of a local.