与指针向量一起使用的最佳智能指针是什么

What is the best smart pointer to use with a pointer vector

本文关键字:指针 最佳 智能 是什么 向量 一起      更新时间:2023-10-16

目前我在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);
    }

在做了一些研究之后,我读到了一些关于自动指针和复制删除的糟糕之处,这在这里似乎并不重要;然而,互联网似乎有一些反对autoptr的东西,大多数人都说应该使用boost::sharedptr。这对我来说似乎是个坏主意,因为这段代码需要很快,而且shared_ptr更重要。

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

任何观点或阅读都将不胜感激。

这一切都与所有权有关。

共享指针真的值得吗?

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

在这里使用自动指针还有其他我不知道的问题吗?

请参阅为什么不赞成使用auto_ptr?以及为什么使用std::auto_ptr<gt;使用标准容器?

最后,在做了研究之后,我似乎找不到是否有一个智能指针最适合boost::ptr_vector?

您可以简单地使用std::vector<std::unique_ptr<x>>std::vector<std::shared_ptr<x>>boost::ptr_vector在C++11AFAIK中不再有任何用处。

如果你坚持保留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<std::unique_ptr<Thread>>