我正在创建一个程序,其中包含一个包含shared_ptr的映射。当我尝试在中找到元素时std::find_if,shared_ptr的引用计数增加。例:
#include <iostream>
#include <memory>
#include <map>
#include <algorithm>
int main(void)
{
std::map<int, std::shared_ptr<int>> map;
map[1] = std::make_shared<int>(3);
map[2] = std::make_shared<int>(5);
map[4] = std::make_shared<int>(-2);
auto it = std::find_if(map.begin(), map.end(),
[](const std::pair<int, std::shared_ptr<int>> &elem) {
std::cout << "find_if: " << elem.second.use_count() << std::endl;
return *elem.second == 5;
});
std::cout << "main: " << it->second.use_count() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
有了这段代码,我得到的输出
find_if: 2
find_if: 2
main: 1
Run Code Online (Sandbox Code Playgroud)
而且我不确定参考计数的增加是否正确。
我正在使用Visual Studio 2017。
c++ ×1