c++ - 与指针 vector 一起使用的最佳智能指针是什么

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

目前我在 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 的智能指针?

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

最佳答案

一切都是关于所有权

Is shared pointer really worth it here?

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

Are there any other issues with using the auto pointer here that I am unaware of?

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

Finally, after doing research I can't seem to find if there is a smart pointer that works best with boost::ptr_vector?

您可以简单地使用 std::vector<std::unique_ptr<x>>std::vector<std::shared_ptr<x>> . boost::ptr_vector 没用在 C++11 AFAIK 中不再存在。

关于c++ - 与指针 vector 一起使用的最佳智能指针是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31790633/

相关文章:

c++ - 模态对话框打开时无法聚焦 Firemonkey 应用程序,除非单击模态对话框本身

c++ - 这个指针值不能转换为整数的规则是什么?

c++ - 通过指向其第一个元素的指针将数组分配给数组

c++ - 使用 boost 库编译 C++ 代码

c++ - 高效流滑动窗口处理的建议

c++ - 用 reintepret_cast 解释对象地址

c - 在 C 中使用 va_list 作为数组

c++ - 处理 IDispatch 参数和 COM

c++ - Boost 没有静态链接到 boost::python 共享对象

c++ - 权重增加的枚举位集。 (C++ & Boost::dynamic_bitset)