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". Shou开发者_运维技巧ld I use this way:
Car &getCar(string model, int year) {
Car c(model, year);
return c;
}
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.
Your problem is:
void displayCar(Car &car) {
cout << car.getModel() << ", " << car.getYear() << endl;
}
you should use a const reference:
void displayCar( const Car & car ) {
cout << car.getModel() << ", " << car.getYear() << endl;
}
This function:
Car getCar(string model, int year) {
Car c(model, year);
return c;
}
is OK as it stands, but all it is doing is what the constructor does, so it is redundant. Passing a value back, rather than a reference, is the right thing to do for this type of function, however, The model parameter should be passed by const reference:
Car getCar( const string & model, int year) {
In general, for class types like string or Car, your default choice for a parameter should always be a const reference.
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;
}
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).
Even better:
Car getCar(string model, int year) {
return Car(model, year);
}
精彩评论