return reference to temporary when dereferencing map iterator

前端 未结 1 952
孤街浪徒
孤街浪徒 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 is not std::pair, but std::pair. Then for return *it;, a temporary std::pair has to be created and returned. (std::pair could be converted from std::pair.) 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& or const std::map::value_type &.

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