I have a class which runs a background task when it is constructed (see the constructor). This task is then stopped and the thread is joined in the destructor when the object is destroyed:
// Foo.hpp -------------------------------
#include <boost/thread.hpp>
#include <boost/date_time/posix_time.hpp>
class Foo {
boost::thread theThread;
Foo();
~Foo();
void bar() const;
}
// Foo.cpp -------------------------------
// This is the background task.
void Foo::bar() const {
while (true) {
try {
// sleep for 1 minute.
boost:this_thread_sleep(boost::posix_time::minutes(1));
// do other stuff endlessly
}
// boost interrupt was called, stop the main loop.
catch (const boost::thread_interrupted&)
{
break;
}
}
// Instantiate background task
Foo::Foo()
: theThread(&Foo::bar, this)
{
// do other stuff
}
// Stop background task
Foo::~Foo() {
theThread.interrupt()
theThread.join();
}
Now this works fine when I have a single instance to the class:
// main.cpp
Foo f;
// do other stuff with f
But when I do this I get a segmentation fault and an aborted message:
// main.cpp
Foo *f;
f = new Foo(); // causes seg fault
delete f;
Why?