boost::shared_ptr boost::mutex 和复制构造函数

2023-12-22

我需要保护对类中数据结构的访问。由于我不能拥有互斥体(因为我无法复制它),我正在考虑拥有shared_ptr并将互斥体保留在那里。这是我的想法的示例代码:

class Sample {
    typedef boost::lock_guard<boost::mutex> AcquireLock;
    boost::shared_ptr<boost::mutex> mutt;

public:
    Sample() : mutt(new boost::mutex) {}

    void Method()
    {
        AcquireLock lock(*mutt);

        //do some work here
    }
};

我有以下问题:

  • 以这种方式使用互斥体(作为类的成员,通过shared_ptr)是一种不好的做法吗?
  • 我是否应该为此类提供复制构造函数,因为它通过共享指针在堆上分配了内存?

编辑:也许我需要提供更多细节: 我将仅创建该对象一次并将其保存在 std::vector 中。我不需要复制它,如果向量需要复制,我不想为每个副本都有不同的互斥体。这就是为什么我认为复制构造函数对我有用。


这种方法非常有效和合法,但请注意,随着班级的发展,您可能希望将相同的技术应用于更多班级成员。这就是为什么我建议您考虑利用 pImpl 惯用法:

// in hpp:
class Sample
{
  Impl();
private:
  struct Impl;
  // compiler generated copy-constructor will copy only this shared_ptr
  shared_ptr<void> pImpl_;
};

// in cpp:
struct Sample::Impl
{
  mutex mut_;
  // put here whatever members you need, extend Impl without affecting the Sample interface
};

Impl::Impl() : pImpl_(new Impl)
{}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

boost::shared_ptr boost::mutex 和复制构造函数 的相关文章

随机推荐