目前我在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的智能指针?
非常感谢任何积分或阅读。
答案 0 :(得分:4)
所有关于所有权。
共享指针真的值得吗?
仅在您需要共享所有权时。如果没有,只需使用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<std::unique_ptr<x>>
或std::vector<std::shared_ptr<x>>
即可。在C ++ 11 AFAIK中不再使用boost::ptr_vector
。
答案 1 :(得分:3)
如果你坚持要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>>
。