开发者

Having trouble with a memory leak - rebinding keys in std::map

开发者 https://www.devze.com 2023-01-27 06:52 出处:网络
void filename_changed(string originalfilename, string newfilename) { auto it = file_source_map.find(originalfilename);
void filename_changed(string originalfilename, string newfilename) {
    auto it = file_source_map.find(originalfilename);
    if (it == file_source_map.end())
        return;
    file_source_map.insert(std::pair<const string, string>(newfilename, it->second));
    file_source_map.erase(originalfilename);
}

I replaced the allocators of std::map and std::string, so I know for certain that this is leaking memory, but I can't see the issue. If originalfilename exists in the map, insert it's value at newfilename, and er开发者_开发问答ase originalfilename.


Except for the simpler (probably replaced while investigating the memory leak)

file_source_map.insert(std::make_pair(newfilename, it->second));
file_source_map.erase(it);

and a check that both filenames are not the same (which would not leak, but actually erase the entry), there is nothing obvious wrong with the code.

Check other things (like the allocators?).


Since keys are unique in std::map, Shouldn't you erase the old key, value and then insert the new key,value?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号