关于c ++:如何使用以std :: weak_ptr为键的std :: map?

How can I use a std::map with std::weak_ptr as key?

如何使用std::weak_ptr作为std::map的键,如以下代码所示?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <map>
#include <memory>

int main()
{
    std::map< std::weak_ptr<int>, bool > myMap;

    std::shared_ptr<int> sharedptr(new int(5));
    std::weak_ptr<int> weakptr = sharedptr;

    myMap[weakptr] = true;

    return 0;
}

上面的程序没有构建,并且尝试编译它会产生许多错误消息,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xfunctional(125): error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const std::tr1::weak_ptr<_Ty>'
1>          with
1>          [
1>              _Ty=int
1>          ]
1>          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xtree(1885) : see declaration of 'std::operator <'
1>          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xfunctional(124) : while compiling class template member function 'bool std::less<_Ty>::operator ()(const _Ty &,const _Ty &) const'
1>          with
1>          [
1>              _Ty=std::tr1::weak_ptr<int>
1>          ]
1>          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\map(71) : see reference to class template instantiation 'std::less<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=std::tr1::weak_ptr<int>
1>          ]
1>          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xtree(451) : see reference to class template instantiation 'std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,_Mfl>' being compiled
1>          with
1>          [
1>              _Kty=std::tr1::weak_ptr<int>,
1>              _Ty=bool,
1>              _Pr=std::less<std::tr1::weak_ptr<int>>,
1>              _Alloc=std::allocator<std::pair<const std::tr1::weak_ptr<int>,bool>>,
1>              _Mfl=false
1>          ]

发生此问题是由于以下行:

1
myMap[weakptr] = true;

错误消息似乎与operator<有关。 我是否需要为weak_ptr定义operator<? 确实,需要定义哪些运算符才能将数据类型用作std::map的键?

(我应该注意,我已经在std命名空间中定义了operator==。此外,我计划将weak_ptr用作自定义类类型,而不是int。)


C ++ 11提供了用于比较std::weak_ptr的适当机制,即:std::owner_less

这应该是地图和集合的默认设置。如果您使用的C ++编译器遇到困难,请尝试使用std::owner_less(如果可用)。如果不可用,则需要提供与std::owner_less类似的机制,以便可以适当地比较std::weak_ptr对象。


如Jody Hagins的答案所述,如果使用std::weak_ptr作为键,则应使用std::owner_less作为关联容器的比较函数对象。我想通过为您的代码提供以下完整的解决方案来扩展该答案:

1
2
3
4
5
6
7
8
9
10
int main() {
    std::map<std::weak_ptr<int>, bool, std::owner_less<std::weak_ptr<int>>> myMap;

    std::shared_ptr<int> sharedptr(new int(5));
    std::weak_ptr<int> weakptr = sharedptr;

    myMap[weakptr] = true;

    return 0;
}

从C ++ 17开始,您可以省略owner_less的template参数,从而缩短代码,如下所示:

1
std::map<std::weak_ptr<int>, bool, std::owner_less<>> myMap;

而且,如果您打算对自定义类使用weak_ptr而不是int,则可以简单地将int替换为类名,如Coliru上的示例代码所示。

通常,除了为(自定义)键类型提供适当的比较功能(或重载operator<)之外,对于std::map也不需要执行任何操作。不需要为密钥类型重载operator==