C++ Returning reference to temporary [duplicate]

2020-03-01 08:25发布

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?

8条回答
等我变得足够好
2楼-- · 2020-03-01 08:54

return AnotherObject(); creates an object which is destroyed before function exit - temporaries are destroyed at the end of the expression that contains them[*], and the expression AnotherObject() creates a temporary.

Since the function returns by reference, this means that by the caller even gets a chance to see that reference, it no longer refers to a valid object.

It would be OK if the function were to return by value, since the temporary would be copied[**].

[*] With a couple of situations that don't, but they don't help you here.

[**] Actually there's an optimization called "copy constructor elision" which means the temporary needn't be created, copied and destroyed. Instead, under certain conditions the compiler is allowed to just create the target of the copy in the same way it would have created the temporary, and not bother with the temporary at all.

查看更多
迷人小祖宗
3楼-- · 2020-03-01 08:58

The function must be declared to return a reference, and a reference has to refer to an object that will continue to exist after the function exits. Your temporary "AnotherObject()" is destructed right after the return, so that obviously won't work. If you can't change the method signature, you may need to throw an exception instead of returning an error value.

查看更多
登录 后发表回答