目前我在 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/