0

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.

joshu
  • 443
  • 8
  • 18
  • 4
    `std::auto_ptr` is __deprecated__. That's IMO good enough a reason not to use it. – emlai Aug 03 '15 at 15:03
  • 5
    Why not just use a `std::vector` that holds `unique_ptr`s? – Cornstalks Aug 03 '15 at 15:06
  • 2
    If you go the std::vector route (very advisable), you might want to read this section on "[thread safety](http://en.cppreference.com/w/cpp/container)". – Hector Aug 03 '15 at 15:15

2 Answers2

4

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.

Community
  • 1
  • 1
emlai
  • 39,703
  • 9
  • 98
  • 145
3

If you insist on keeping boost::ptr_vector, I'd suggest just moving to this:

for(; numThreads <  numberOfWorkers; ++numThreads)
{
    m_workerThreads.push_back(new Thread);
}

for(size_t x = 0; x < m_workerThreads.size(); ++x)
{
   m_workerThreads[x]->Start();
}

However, personally, I would just move to std::vector<std::unique_ptr<Thread>>.

Chad
  • 17,839
  • 4
  • 46
  • 62