一个关于const 变量作为map键值的Bug

struct Instance{
    int _type;
    AtrVec _attri_list;
    Instance(){

    }
    float getAttriValue(const proto::Attribute& attri) const{
        if(_attri_list.find(attri) == _attri_list.cend()){
            std::cout<<"ERROR : Attribute didn't exist ins AtrVec.";
        }
        return _attri_list.at(attri);
    }
};

这里当使用 cons Instance 调用函数时,只可以使用 const Attribute 作为键值,但是 map [] 运算符不是const函数,因此会报错,使用 map 的 at 方法可以避免,因为

      mapped_type&
      at(const key_type& __k)
      {
    iterator __i = lower_bound(__k);
    if (__i == end() || key_comp()(__k, (*__i).first))
      __throw_out_of_range(__N("map::at"));
    return (*__i).second;
      }

      const mapped_type&
      at(const key_type& __k) const
      {
    const_iterator __i = lower_bound(__k);
    if (__i == end() || key_comp()(__k, (*__i).first))
      __throw_out_of_range(__N("map::at"));
    return (*__i).second;
      }

既有const 定义,又有非const 定义.

参考

猜你喜欢

转载自www.cnblogs.com/walnuttree/p/12200612.html