idealvin / coost

A tiny boost library in C++11.
Other
3.91k stars 558 forks source link

co::lru_map insert 问题 #332

Closed lzhkui closed 11 months ago

lzhkui commented 1 year ago
    // The key is not inserted if it already exists.
    template<typename Key, typename Val>
    void insert(Key&& key, Val&& value) {
        if (_kv.size() >= _capacity) {
            K k = _kl.back();
            _kl.pop_back();
            _kv.erase(k);
            _ki.erase(k);
        }
        auto r = _kv.emplace(std::forward<Key>(key), std::forward<Val>(value));
        if (r.second) {
            // key如果是右值,forward进_kv.emplace(),可能会被move进去了,也就是这里再用的话可能是未定义行为,表现为key是空值
            // 我看现有的lru_map测试用例只有key是int的情况,可以增加std::string或者自定义结构体测试一下
            // _kl.push_front(key);
            // _ki[key] = _kl.begin();
            // 稍作改动即可,避免这种情况
            _kl.push_front(r.first->first);
            _ki[r.first->first] = _kl.begin();
        }
    }
idealvin commented 12 months ago

@lzhkui 是的,感谢指出