在 2 个对象之间共享容器的提示

Tips to share container between 2 objects?

本文关键字:提示 共享 之间 对象      更新时间:2023-10-16

我有一些STL容器,我需要在2种不同类型的对象之间共享 - 比如A和B。容器在类 A 中定义,并在类 B 中用作引用。由于 STL 容器不是线程安全的,我计划在 A 中定义 boost::mutex 并将其作为引用存储在类 B 中。

这个计划显然失败了,因为我意识到boost::mutex是不可复制的。我无法将容器移出类 A 或在容器上提供包装器。你会在这里做什么?

为什么不能复制互斥体?

我不是 100% 确定我可以遵循,但是如果您想在一个类的两个实例之间共享互斥锁以保护共享资源,为什么不只使用 boost::shared_ptr<boost::mutex> 从两个实例访问互斥锁?

当您需要共享资源时,这应该是一个通用策略,您也可以考虑将boost::shared_ptr用于容器本身,但如果没有看到您的代码,很难提供一些具体的建议。

class Sample
{
  std::vector<int> v;
private:
  struct Mut;
};
struct Sample::Mut
{
  boost::mutex mut_;
};

class Sample {
    std::vector<int> v;
public:
    boost::shared_ptr<boost::mutex> mutt;
    Sample() : mutt(new boost::mutex) {}
};

现在,您可以在提供互斥包装器访问权限的其他对象中引用此示例的boost::mutex,或者可以使用Mut结构或boost::shared_ptr的副本直接初始化这些对象。 boost::shared_ptr可复制的,它的所有副本都将共享给定的互斥锁。


为什么不能复制互斥体?

因为互斥锁是不可复制的。这是它派生自boost::noncopyable

#include <boost/thread/mutex.hpp>
class mutex:
    boost::noncopyable
{

不可复制类是一个基类。 从中派生您自己的类 不可复制,当您想要禁止复制构造和复制时 分配。

事实上,您不需要它们的副本,因为它毫无用处,而是您希望在许多对象中共享相同的实例,并引用保护对单个资源的访问的单个互斥锁。

<boost/noncopyable.hpp>

//  Private copy constructor and copy assignment ensure classes derived from
//  class noncopyable cannot be copied.
//  Contributed by Dave Abrahams
namespace noncopyable_  // protection from unintended ADL
{
  class noncopyable
  {
   protected:
#ifndef BOOST_NO_DEFAULTED_FUNCTIONS
    BOOST_CONSTEXPR noncopyable() = default;
    ~noncopyable() = default;
#else
    noncopyable() {}
      ~noncopyable() {}
#endif
#ifndef BOOST_NO_DELETED_FUNCTIONS
        noncopyable( const noncopyable& ) = delete;
        noncopyable& operator=( const noncopyable& ) = delete;
#else
    private:  // emphasize the following members are private
      noncopyable( const noncopyable& );
      noncopyable& operator=( const noncopyable& );
#endif
  };
}
typedef noncopyable_::noncopyable noncopyable;