Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Returning reference to temporary [duplicate]

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?

like image 476
dcinadr Avatar asked Apr 14 '11 17:04

dcinadr


1 Answers

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.

like image 154
zdan Avatar answered Sep 30 '22 00:09

zdan