在包含shared_ptr的地图上使用find_if会增加引用计数 [英] Using find_if on map containing shared_ptr increases ref count

查看:73
本文介绍了在包含shared_ptr的地图上使用find_if会增加引用计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个程序,其中包含一个包含shared_ptr的映射.当我尝试使用 std :: find_if 在其中查找元素时,shared_ptr的引用计数会增加.示例:

I'm creating a program which has a map containing shared_ptr's. And when I try to find an element in it with std::find_if, the reference count of the shared_ptr increases. Example:

#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;
}

使用此代码,我得到的输出

With this code I get the output of

find_if: 2
find_if: 2
main: 1

我不确定引用计数的增加是否正确.

and I'm not sure if the reference count increase is proper behaviour.

我正在使用Visual Studio 2017.

I'm using Visual Studio 2017.

推荐答案

问题是您的lambda参数的类型

The problem is the type of the parameter of your lambda

const std::pair<int, std::shared_ptr<int>> &

...这不符合 std :: map<< int,std :: shared_ptr< int>>> :: value_type (密钥类型缺少 const ).

...this does not correspond to std::map<<int, std::shared_ptr<int>>>::value_type (you are missing the const for the key type).

因此,为了调用您的lambda,必须从 std构造一个类型为 std :: pair< int,std :: shared_ptr< int> 的临时对象:: pair< const int,std :: shared_ptr< int>> 存储在 std :: map 中.

Thus, in order to call your lambda, a temporary object of type std::pair<int, std::shared_ptr<int>> has to be constructed from the std::pair<const int, std::shared_ptr<int>> stored in the std::map.

构造此对象时,将复制 shared_ptr ,因此必须增加其引用计数器.

When this object is constructed, the shared_ptr is copied, so its reference counter has to be incremented.

如果将参数类型更改为

const std::pair<const int, std::shared_ptr<int>> &

...问题消失了.您也可以在这里使用 const auto& 代替完整类型.

...the problem disapears. You could also use const auto& instead of the full type here.

1 如果在此处使用非 const 引用,则会出现编译器错误,因为您无法初始化类型为 std的引用:: pair< int,std :: shared_ptr< int>> 来自 std :: pair< const int,std :: shared_ptr< int> ,但> const -reference允许使用临时名称代替​​.

1 If you use a non-const reference here, you'll get a compiler error because you cannot initialize a reference of type std::pair<int, std::shared_ptr<int>> from a std::pair<const int, std::shared_ptr<int>>, but a const-reference allow a temporary to be used instead.

这篇关于在包含shared_ptr的地图上使用find_if会增加引用计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆