C++ 在包含共享\u ptr的地图上使用find_if会增加ref计数
我正在创建一个程序,它有一个包含共享\u ptr的映射。当我试图用C++ 在包含共享\u ptr的地图上使用find_if会增加ref计数,c++,C++,我正在创建一个程序,它有一个包含共享\u ptr的映射。当我试图用std::find_if在其中查找元素时,共享的ptr的引用计数会增加。例如: #include <iostream> #include <memory> #include <map> #include <algorithm> int main(void) { std::map<int, std::shared_ptr<int>> map;
std::find_if
在其中查找元素时,共享的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;
}
我不确定参考计数的增加是否是正确的行为
我正在使用Visual Studio 2017。问题在于lambda的参数类型
const std::pair<int, std::shared_ptr<int>> &
…问题不存在了。您也可以使用const auto&
而不是此处的完整类型
1如果在此处使用非常量
引用,则会出现编译器错误,因为无法从std::pair
中初始化类型为std::pair
的引用,但常量
-引用允许使用临时引用
const std::pair<int, std::shared_ptr<int>> &
const std::pair<const int, std::shared_ptr<int>> &