return reference to temporary when dereferencing map iterator

前端 未结 1 953
孤街浪徒
孤街浪徒 2021-01-13 04:44

Consider this code

#include 
#include 

const int& foo(const std::vector& x,unsigned i) {
    auto it = x.be         


        
相关标签:
1条回答
  • 2021-01-13 05:25

    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.

    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 &.

    0 讨论(0)
提交回复
热议问题