0

Today I want to use a boost::scoped_ptr to point to a boost::thread.

In my Thread.h I have boost::scoped_ptr<boost::thread> m_thread and in my Thread.cpp there's a function create() in which the creation of the boost::thread should take place. I tried Thread::m_thread (new boost::thread(attr, boost::bind(%Thread::run, this))); but unsurprisingly it didn't work.

I can't figure out myself (or by using the boost documentation) how I would do this, since I don't fully understand what's happening with the scoped_ptr and how it works. Before I used to use a raw pointer, which worked fine but I'm not allowed to use it at this point.

Thanks for your time!

DenverCoder21
  • 879
  • 3
  • 16
  • 34

1 Answers1

1

I don't know what kind of error your got, try this:

class Thread {
 public:
  Thread() : thread_(new boost::thread(boost::bind(&Thread::run, this))) {
  }

  void run() {
  }

  ~Thread() {
    thread_->join();
  }

 private:
  boost::scoped_ptr<boost::thread> thread_;
};

int main() {
  Thread thread;
}

But do not forget, that thread may start before constructor end his job.

  • That's pretty much what I tried and what's stated in my question if I'm not missing something. ;) My error is about the definition of m_thread and it says: _error C2064: term does not evaluate to a function taking 1 arguments_ That's regarding the line with `Thread::m_thread(new boost::thread(attr, boost::bind(&Thread::run, this)));` – DenverCoder21 Aug 29 '13 at 08:14
  • Hey, `m_thread` is declared in **Thread.h** and called in `create()` function within **Thread.cpp**. However, the issue (most likely) was that after creating a Thread Object, `m_thread` is already defined with a default value internally and thus can't be overwritten in the `create()` function. I'm creating another `scoped_ptr` called `tmp` in `create()` and assign my `boost::thread` to it, then swapping it with `m_thread` and destroying it automatically when it goes out of scope after finishing `create()`. Might no be the most beauftiful thing to do, but works for me. Thanks for your help! – DenverCoder21 Aug 29 '13 at 16:18