Show memory_bug.cc syntax highlighted
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/xtime.hpp>
using namespace std;
using namespace boost;
/* This experiment is meant to show that memory allocation is working properly
* as thread start and end, even when detached. */
template<class T>
class ThreadDelegate
{
shared_ptr<T> target;
public:
ThreadDelegate(const shared_ptr<T> &t) : target(t) {}
ThreadDelegate(const ThreadDelegate& b) {
this->target = b.target;
}
ThreadDelegate &operator=(const ThreadDelegate &b) {
this->target = b.target;
}
void operator()() { (*target)(); }
};
class A
{
public:
A() { cout << "A() called." << endl; }
A(const A &b) { cout << "ERROR: Copy constructor called!" << endl; }
~A() { cout << "~A() called." << endl; }
A& operator=(const A &b) { cout << "ERROR: assignment called!" << endl; }
void operator()() {
xtime xt;
cout << "Thread started" << endl;
xtime_get(&xt, boost::TIME_UTC);
xt.sec += 1;
thread::sleep(xt);
cout << "Thread ended" << endl;
}
};
int main()
{
xtime xt;
for(int i=0; i<25; i++) {
xtime_get(&xt, boost::TIME_UTC);
xt.sec += 2;
thread::sleep(xt);
shared_ptr<A> p(new A());
ThreadDelegate<A> obj(p);
cout << "Thread detached";
thread t(obj);
}
xtime_get(&xt, boost::TIME_UTC);
xt.sec += 5;
thread::sleep(xt);
}
See more files for this project here