Back link to temporary when dereferencing cards are named

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?

+4
source share
1 answer

The problem is that value_type std::map<int,int>not std::pair<int,int>, but std::pair<const int,int>. Then for return *it;you need to create and return a temporary one std::pair<int,int>. ( std::pair<int,int>can be converted from std::pair<const int,int>.) Temporary will be destroyed immediately and leave the returned link cheated.

, const std::pair<const int,int>& const std::map<int,int>::value_type &.

+6

Source: https://habr.com/ru/post/1695273/


All Articles