Opened 16 years ago

Closed 16 years ago

#610 closed Bugs (Rejected)

object destructor called four times when using thread

Reported by: nobody Owned by: Roland Schwarz
Milestone: Component: threads
Version: None Severity:
Keywords: Cc:

Description

franzronan@yahoo.com

I created this test application, I don't know if I 
implemented it right but I got four calls on the class 
test destructor... current lib version 1.32

#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <iostream>

using namespace std;

class test {
  public:
      test() {
        cout << "constructor" << endl;
      };
     
      ~test() {
        cout << "destructor" << endl;
      };

      void operator()() {
        boost::xtime xt;
        boost::xtime_get(&xt, boost::TIME_UTC);
        xt.sec += 5;
        boost::thread::sleep(xt);
        cout << "sleep" << endl;
      };
};

int main(int argc, char *argv[]) {
  //test scope
  {
    test* a = new test();
    boost::thread* thrd=new boost::thread(*a);
    //got for desctructor calls...
    thrd->join();
  }
}

Change History (2)

comment:1 by zigmar, 16 years ago

Logged In: YES 
user_id=571891

You pass the test object (a) by value, so the behaviour is
probably correct. When you see, is the destruction of
temporary objects. You will able to see their construction
if you add custom copy constuctor to test class. Now, you
print the message only when original object is created, but
not when it copy-constructed. Try this:

class test {
public:
  test() {
    cout << "constructor" << endl;
  };

  test(const test&) {
    cout << "copy constructor" << endl;
  };

  ~test() {
    cout << "destructor" << endl;
  };
};

comment:2 by Roland Schwarz, 16 years ago

Status: assignedclosed
Logged In: YES 
user_id=541730

This is a consequence of your code tracing only default
constructor calls, and all destructor calls.
If you override the default compiler generated copy
constructor like:

test(const test& t) {
  *this = t;
  cout << "copyconstructor" << endl;
}

you will see that each constructor call indeed is matched by
a destructor call. (with exception of course that you code
never destroys a, which leaves a leak)

Note: See TracTickets for help on using tickets.