【发布时间】:2012-10-04 05:57:13
【问题描述】:
如何使用std::weak_ptr 作为std::map 的键,如以下代码所示?
#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>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> ]
由于以下行导致问题发生:
myMap[weakptr] = true;
错误消息似乎与operator< 有关。我需要为weak_ptr 定义operator< 吗?确切地说,需要定义哪些运算符才能将数据类型用作std::map 的键?
(我应该注意到我已经在std 命名空间中定义了operator==。另外,我计划将weak_ptr 用于自定义类类型,而不是int。)
【问题讨论】:
-
指向具有相同值的不同
int对象的指针应该相等还是不同? IE。auto first = std::make_shared(5); auto second = std::make_shared(5); myMap[first] = true; myMap[second] = false;应该有多少元素?
标签: c++ dictionary stdmap weak-references weak-ptr