Boost logo

Boost Users :

Subject: Re: [Boost-users] functor for boost::thread_group threads: which one is correct?
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2009-08-23 15:06:20


AMDG

Boost lzw wrote:
> I have two versions (VERSION1 and VERSION2) of a group_helper functor to be
> called from boost::thread_group, which one of them is correct?
>
> class FileThread
> {
> public:
> void print() {...}
> void find() {...}
> };
>
> class group_helper
> {
> private:
> boost::shared_ptr<FileThread> m_object;
> public:
> //VISION1
> group_helper(boost::shared_ptr<FileThread>& object) : m_object(object) {
> }
>
> //VISION2
> group_helper() : m_object(boost::shared_ptr<FileThread>(new FileThread))
> { }
>
> void operator()() { m_object->find(); m_object->print(); }
> };
>

Both are correct depending on whether you want to pass an external
FileThread
or create a new FileThread in the constructor.

> On another matter, why the following code results in a runtime exception
> from the group_helper's dtor?
>
> #include <iostream>
> #include "boost/thread/thread.hpp"
>
> class FileThread
> {
> public:
> void find() { }
> void print() { }
> };
>
> class group_helper
> {
> private:
> FileThread* m_object;
> public:
> group_helper() : m_object(new FileThread) {}
> void operator()() { m_object->find(); m_object->print(); }
> ~group_helper() { if (m_object) delete m_object; }// EXCEPTION from dtor
> };
>

group_helper is copied and both copies try to
delete m_object.

> int main()
> {
> group_helper gh;
> boost::thread thrd(gh);
> thrd.join();
> }
>

In Christ,
Steven Watanabe


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net