Possible Duplicate:
warning: returning reference to temporary
I am getting the error "returning reference to temporary" on the second line below.
class Object : public std::map <ExString, AnotherObject> const {
public:
const AnotherObject& Find (const ExString& string ) const {
Object::const_iterator it = find (string);
if (it == this->end()) { return AnotherObject() };
return ( it->second );
}
}
My class implements std::map.
I am new to C++ so I'm guessing its just a syntax error. Any help?
If your function looks like this:
AnotherObject& getAnotherObject()
{
. . .
Object::const_iterator it = find ("lang");
if (it == this->end()) { return AnotherObject() };
. . .
}
the problem is that the AnotherObject() you've returned will be destroyed as soon as the function exits, and so the caller to your function will have a reference to a bogus object.
If your function returned by value however:
AnotherObject getAnotherObject()
then a copy will be made before the original is destroyed and you'll be OK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With