Search code examples
c++pointersboostsmart-pointersptr-vector

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


Currently I have a class that looks like this in 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;
};

And later in the constructor I do this (in the 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);
    }

After doing some research I have read some bad things about auto pointers and delete on copy which doesn't really seem to matter here; however, it seems that the internet has something against auto_ptr with most people saying to use boost::shared_ptr instead. This seems like a bad idea to me since this code needs to be fast and the shared_ptr is more exspensive.

I was wondering if anyone could give me some insight on this code. Is shared pointer really worth it here? Are there any other issues with using the auto pointer here that I am unaware of? Finally, after doing research I can't seem to find if there is a smart pointer that works best with boost::ptr_vector?

Any points or reading are much appreciated.


Solution

  • It's all about ownership.

    Is shared pointer really worth it here?

    Only if you need shared ownership. If not, simply use std::unique_ptr.

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

    See Why is auto_ptr being deprecated? and 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?

    You can simply use std::vector<std::unique_ptr<x>> or std::vector<std::shared_ptr<x>>. There's no use for boost::ptr_vector anymore in C++11 AFAIK.