我想比较两个std :: weak_ptr或一个std :: weak_ptr和一个std :: shared_ptr的相等性.
我想知道的是weak_ptr/shared_ptr指向的每个对象是否相同.比较应该产生负面结果,不仅如果地址不匹配,而且如果基础对象被删除然后偶然使用相同地址重建.
所以基本上,即使分配器保留相同的地址,我也希望这个断言成立:
auto s1 = std::make_shared<int>(43);
std::weak_ptr<int> w1(s1);
s1.reset();
auto s2 = std::make_shared<int>(41);
std::weak_ptr<int> w2(s2);
assert(!equals(w1,w2));
Run Code Online (Sandbox Code Playgroud)
weak_ptr模板不提供相等的运算符,正如我所理解的那样,这是有充分理由的.
所以一个天真的实现看起来像这样:
template <typename T, typename U>
inline bool naive_equals(const std::weak_ptr<T>& t, const std::weak_ptr<U>& u)
{
return !t.expired() && t.lock() == u.lock();
}
template <typename T, typename U>
inline bool naive_equals(const std::weak_ptr<T>& t, const std::shared_ptr<U>& u)
{
return !t.expired() && t.lock() == u;
}
Run Code Online (Sandbox Code Playgroud)
如果第一个weak_ptr在此期间到期,则它会产生0.如果不是,我将weak_ptr升级为shared_ptr并比较地址.
这个问题是我必须锁定weak_ptr两次(一次)!我担心花费太多时间.
我想出了这个:
template <typename T, typename U>
inline bool equals(const …Run Code Online (Sandbox Code Playgroud) 在阅读了关于operator <for std :: weak_ptr的讨论之后,我看不出有什么理由为什么定义std :: hash来使用std :: weak_ptr的控制块是行不通的.我也无法相信标准委员会忽视了这一点.有没有人阅读有关该主题的相关讨论?
编辑:讨论运营商<for std :: weak_ptr http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1590.html