取消引用地图迭代器时,返回对临时对象的引用 [英] return reference to temporary when dereferencing map iterator
问题描述
考虑此代码
#include <iterator>
#include <vector>
const int& foo(const std::vector<int>& x,unsigned i) {
auto it = x.begin();
std::advance(it,i);
return *it;
}
clang和gcc都不会发出错误/警告,但这是
Both clang and gcc emit no errors/warnings, but this:
#include <iterator>
#include <map>
const std::pair<int,int>& bar(const std::map<int,int>& x,unsigned i){
auto it = x.begin();
std::advance(it,i);
return *it;
}
使用 clang 编译,并使用-Werror
结果:
compiled with clang and using -Werror
results in :
<source>:14:12: error: returning reference to local temporary object [-Werror,-Wreturn-stack-address]
return *it;
^~~
以及 gcc :
<source>: In function 'const std::pair<int, int>& bar(const std::map<int, int>&, unsigned int)':
<source>:14:13: error: returning reference to temporary [-Werror=return-local-addr]
return *it;
^~
是什么使gcc和clang拒绝bar
?为什么foo
还可以?
What makes gcc and clang reject bar
and why is foo
fine?
推荐答案
问题是std::map<int,int>
不是std::pair<int,int>
,而是std::pair<const int,int>
.然后对于return *it;
,必须创建并返回一个临时std::pair<int,int>
. (std::pair<int,int>
可能是std::pair<const int,int>
中的转换.)临时文件将被立即销毁,并将返回的参考物悬挂起来.
The problem is that the value_type
of std::map<int,int>
is not std::pair<int,int>
, but std::pair<const int,int>
. Then for return *it;
, a temporary std::pair<int,int>
has to be created and returned. (std::pair<int,int>
could be converted from std::pair<const int,int>
.) The temporary will be destroyed immediately and left the returned reference dangled.
要解决问题,您可以将返回类型更改为const std::pair<const int,int>&
或const std::map<int,int>::value_type &
.
To sovle the issue you can change the return type to const std::pair<const int,int>&
or const std::map<int,int>::value_type &
.
这篇关于取消引用地图迭代器时,返回对临时对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!