【问题标题】:What is the best smart pointer to use with a pointer vector与指针向量一起使用的最佳智能指针是什么
【发布时间】:2015-08-03 15:02:06
【问题描述】:

目前我在 threadhelper.hpp 中有一个看起来像这样的类:

class Thread : public Helper<finder>{ 
/* lots of helper function*/
public:
    Thread();
    startThread(const std::string& name);
private:
    Thread(const Thread&);
    Thread & operator=(const Thread&);
    boost::ptr_vector<thread::Foo<Bar> > m_workerThreads;
};

稍后在构造函数中我会这样做(在 cpp 中):

Thread::Thread()
{
    /*bunch of other stuff here.*/
    for(; numThreads <  numberOfWorkers; ++numThreads)
    {
        std::auto_ptr<thread::Foo<Bar> > newThread(new Thread());
        newThread->startThread();
        m_workerThreads.push_back(newThread);
    }

在做了一些研究之后,我读到了一些关于自动指针和删除副本的不好的东西,这在这里似乎并不重要;但是,似乎互联网上有一些反对 auto_ptr 的东西,大多数人都说要使用 boost::shared_ptr 。这对我来说似乎是个坏主意,因为此代码需要快速且 shared_ptr 更昂贵。

我想知道是否有人可以给我一些关于这段代码的见解。共享指针在这里真的值得吗?在这里使用自动指针还有其他我不知道的问题吗?最后,经过研究,我似乎无法找到最适合 boost::ptr_vector 的智能指针?

非常感谢任何观点或阅读。

【问题讨论】:

  • std::auto_ptr弃用。这就是 IMO 足够好的理由不使用它。
  • 为什么不直接使用包含unique_ptrs 的std::vector
  • 如果你走 std::vector 路线(非常可取),你可能想阅读关于“thread safety”的这一部分。

标签: c++ pointers boost smart-pointers ptr-vector


【解决方案1】:

一切都是关于所有权

共享指针在这里真的值得吗?

仅当您需要共享所有权时。如果没有,只需使用std::unique_ptr

在此处使用自动指针是否还有其他我不知道的问题?

Why is auto_ptr being deprecated?Why is it wrong to use std::auto_ptr<> with standard containers?

最后,经过研究,我似乎无法找到最适合 boost::ptr_vector 的智能指针?

您可以简单地使用std::vector&lt;std::unique_ptr&lt;x&gt;&gt;std::vector&lt;std::shared_ptr&lt;x&gt;&gt;。在 C++11 AFAIK 中,boost::ptr_vector 不再有用了。

【讨论】:

    【解决方案2】:

    如果您坚持保留boost::ptr_vector,我建议您直接移至此:

    for(; numThreads <  numberOfWorkers; ++numThreads)
    {
        m_workerThreads.push_back(new Thread);
    }
    
    for(size_t x = 0; x < m_workerThreads.size(); ++x)
    {
       m_workerThreads[x]->Start();
    }
    

    但是,就我个人而言,我会转至std::vector&lt;std::unique_ptr&lt;Thread&gt;&gt;

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 2021-07-03
      • 2020-12-04
      相关资源
      最近更新 更多