C ++返回对临时的引用 [英] C++ Returning reference to temporary
本文介绍了C ++返回对临时的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
警告:返回引用临时
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 );
}
}
我的类实现std :: map。
My class implements std::map.
我是C ++的新手,所以我猜测它只是一个语法错误。任何帮助?
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() };
. . .
}
问题是你返回的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.
如果你的函数返回的值是函数返回的值,那么函数返回值为:/ p>
If your function returned by value however:
AnotherObject getAnotherObject()
b $ b
那么在原件被销毁之前将会进行复制,你就OK了。
then a copy will be made before the original is destroyed and you'll be OK.
这篇关于C ++返回对临时的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文