Hi Steven and other guys,

Thanks for Steven's input. Is the following code correct?
class FileThread
{
public:
    void find() { std::cout << "FileThread::find() called" << std::endl;}
    void print() { std::cout << "FileThread::print() called" << std::endl;}
};

class group_helper           
{                           
private:
    boost::shared_ptr<FileThread> m_object;   
public:                       
    group_helper() : m_object(boost::shared_ptr<FileThread>(new FileThread))
             { std::cout << "group_helper::ctor called" << std::endl;}
    void operator()() { m_object->find(); m_object->print(); }
    ~group_helper() { std::cout << "group_helper::***dtor called" << std::endl; }
};

int main()
{
    group_helper gp;
    boost::thread_group threads;
        for (int i = 0; i < 1; ++i)
            threads.create_thread(gp);       
        threads.join_all();                   

    return 0;
}
===========
Output: 1 call to "group_helper::ctor called"
    6 calls to "group_helper::***dtor called"
===========
If the code is correct, does this mean that with thread_group we can no longer expect the # of ctors matches that of the dtors in threaded code?

Thanks in advance,
Robert



On Sun, Aug 23, 2009 at 3:06 PM, Steven Watanabe <watanabesj@gmail.com> wrote:
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 mailing list
Boost-users@lists.boost.org
http://lists.boost.org/mailman/listinfo.cgi/boost-users