问题是 lambda 参数的类型
const std::pair<int, std::shared_ptr<int>> &
...这不对应于std::map<<int, std::shared_ptr<int>>>::value_type(你错过了const
对于密钥类型)。
因此,为了调用 lambda,类型的临时对象std::pair<int, std::shared_ptr<int>>
必须从构建std::pair<const int, std::shared_ptr<int>>
存储在std::map
.
当这个对象被构造时,shared_ptr
被复制,因此它的引用计数器必须递增。
如果将参数类型更改为
const std::pair<const int, std::shared_ptr<int>> &
……问题就消失了。你也可以使用const auto&
而不是这里的完整类型。
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.