Consider this code
#include <iterator>
#include <vector>
const int& foo(const std::vector<int>& x,unsigned i) {
auto it = x.begin();
std::advance(it,i);
return *it;
}
Both clang and gcc do not give any 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;
}
compiled with clang and using the -Werrorresults:
<source>:14:12: error: returning reference to local temporary object [-Werror,-Wreturn-stack-address]
return *it;
^~~
and 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;
^~
What does gcc and clang reject barand why is fooexcellent?
source
share