[英]Is it safe to use a weak_ptr in a std::set or key of std::map
[英]std::map with std::weak_ptr key
我有一個關於使用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_ptrs定義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
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.