15

我有一套这样的:set<weak_ptr<Node>, owner_less<weak_ptr<Node> > > setName;

它工作正常。但我想将其更改为无序集。但是,当我这样做时,我得到了大约六页的错误。任何想法如何做到这一点?

在浏览了所有错误消息页面后,我发现可能有帮助的行。

/usr/include/c++/4.7/bits/functional_hash.h:60:7: error: static assertion failed: std::hash is not specialized for this type
/usr/include/c++/4.7/bits/stl_function.h: In instantiation of ‘bool std::equal_to<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = std::weak_ptr<Node>]’:
4

4 回答 4

25

简短而不幸的答案是,虽然shared_ptr<>可以安全地用作无序集合或映射中的键,weak_ptr<>但不能也不能。再多的诡计也无法保证安全。

这是因为weak_ptr的接口不公开对共享控件对象的访问,这是owner_before()在有序集合或映射中使用时比较的基础。

虽然锁定指针然后对 进行哈希处理似乎是合理的shared_ptr,但事实并非如此。如果最后一个shared_ptr超出范围,则哈希值将更改,这将导致下次迭代您的 set 或 map 时出现未定义的行为。这很可能不会被注意到,直到您的代码在客户面前投入生产,您偶尔会遇到意外和莫名其妙的功能损失,但是您的单元测试仍然会完美地通过,让您错误地认为您的测试覆盖率很好,你的代码是可靠的,应该归咎于用户、硬件或网络。

所以,总而言之,如果你要使用weak_ptr's 来构建你的非拥有对象缓存(它们非常好),你需要使用 astd::set<weak_ptr>并遭受微小的性能损失(尽管实际上这将与性能损失相形见绌由mutex保护集合的 引起的)。

如果您真的想使用 aweak_ptr作为无序键,您将不得不自己编写(提示:使用共享控制块的地址作为散列函数的基础)。

于 2015-06-18T17:49:24.873 回答
10

我不认为建议的哈希函数是正确的。如果指向对象的所有共享指针都消失了,那么weak_ptr<X>::lock()将返回空的 shared_ptr,其哈希值可能为零。所以哈希函数可以在整个时间返回不同的值。

我认为这里正确的解决方案是使用 boost::unordered_map<X*, boost::weak_ptr<X>>. 类型X*可以很容易地用作散列映射的键,并且weak_ptr<X>值使您有机会找出引用的对象是否仍然存在。

要将值存储到此哈希中,您可以使用以下内容:

if (boost::shared_ptr<X> p = wp.lock()) {
    // weak_ptr is still valid
    ptrs.insert(std::make_pair(p.get(), p));
}
于 2014-03-01T05:48:06.673 回答
1

请阅读下面的Richard Hodges答案,因为我的答案是不正确的,尽管它是公认的解决方案。


由于unordered_sets是基于散列的,因此您必须为std::weak_ptr 数据类型提供散列函数对象。

如果您查看 unordered_set 模板参数

template<class Key,
    class Hash = std::hash<Key>,
    class Pred = std::equal_to<Key>,
    class Alloc = std::allocator<Key> >
    class unordered_set;

您会注意到 std::unordered_set 为您提供了默认的 std::hash<> 模板参数。但由于 std::hash 只提供特定数据类型集的特化,您可能必须提供自己的。

您引用的错误消息告诉您, std::hash<> 不存在 std::weak_ptr<> 的专门化,因此您必须为此提供自己的散列函数:

template<typename T>
struct MyWeakPtrHash : public std::unary_function<std::weak_ptr<T>, size_t> {
   size_t operator()(const std::weak_ptr<T>& wp)
   {
      // Example hash. Beware: As zneak remarked in the comments* to this post,
      // it is very possible that this may lead to undefined behaviour
      // since the hash of a key is assumed to be constant, but will change
      // when the weak_ptr expires
      auto sp = wp.lock();
      return std::hash<decltype(sp)>()(sp);
   }
};

编辑: 您还需要提供一个相等函数,因为没有为 weak_ptr 提供 std::equal_to 。从Stackoverflow 上的“Equality-compare std::weak_ptr”采取一种可能的方法:

template<typename T>
struct MyWeakPtrEqual : public std::unary_function<std::weak_ptr<T>, bool> {

   bool operator()(const std::weak_ptr<T>& left, const std::weak_ptr<T>& right)
   {
      return !left.owner_before(right) && !right.owner_before(left);
   }
};

所有这些都为我们提供了以下信息:

std::unordered_set<std::weak_ptr<T>,
                   MyWeakPtrHash<T>,
                   MyWeakPtrEqual<T>> wpSet;
于 2012-12-04T15:30:15.693 回答
1

这里给出了一个可行的解决方案:如何计算 std::weak_ptr 的哈希值?下面是一个略微扩展的变体,它添加了缺失的细节。与上面给出的早期答案不同,这是有效的,因为哈希是在shared_ptr计数降至零之前计算和存储的。

namespace foobar
{
// Public inheritance was used to avoid having to
// duplicate the rest of the API. Unfortunately this
// allows object slicing. So, an alternate solution is
// to use private inheritance, and `using` to provide
// the missing API.
template<class T>
struct hashable_weak_ptr : public std::weak_ptr<T>
{
   hashable_weak_ptr(std::shared_ptr<T>const& sp) :
      std::weak_ptr<T>(sp)
   {
      if (!sp) return;
      _hash = std::hash<T*>{}(sp.get());
   }

   std::size_t get_hash() const noexcept { return _hash; }

   // Define operator<() in order to construct operator==()
   // It might be more efficient to store the unhashed
   // pointer, and use that for equality compares...
   friend bool operator<(hashable_weak_ptr const& lhs,
                         hashable_weak_ptr const& rhs)
   {
      return lhs.owner_before(rhs);
   }
   friend bool operator!=(hashable_weak_ptr const& lhs,
                          hashable_weak_ptr const& rhs)
   {
      return lhs<rhs or rhs<lhs;
   }
   friend bool operator==(hashable_weak_ptr const& lhs,
                          hashable_weak_ptr const& rhs)
   {
      return not (lhs != rhs);
   }
   private:
      std::size_t _hash = 0;
};
} // namespace foobar

namespace std
{

// Specializations in std namespace needed
// for above to be usable.
template<class T>
struct owner_less<foobar::hashable_weak_ptr<T>>
{
   bool operator()(const foobar::hashable_weak_ptr<T>& lhs,
                   const foobar::hashable_weak_ptr<T>& rhs) const noexcept
   {
      return lhs.owner_before(rhs);
   }
};

template<class T>
struct hash<foobar::hashable_weak_ptr<T>>
{
   std::size_t operator()(const foobar::hashable_weak_ptr<T>& w) const noexcept
   {
      return w.get_hash();
   }
};
} // namespace std

这里首先提出了这个问题的一个变体:为什么在 C++0x 中没有为 std::weak_ptr 定义 std::hash?解决此问题的最新标准委员会草案在这里:JTC1 WG21 P1901

于 2021-11-27T21:55:57.137 回答