views:

61

answers:

1

I have the following code (this is some semi-sudo code, which may not compile):

class FooBar {
public:
    void a();
    void b();
    boost::shared_ptr<boost::thread> m_thread;
    std::string m_test;
};

void FooBar::a() {
    m_test = "Foo bar"
    m_thread = shared_ptr<thread>(new thread(bind(&FooBar::b, this)));
}

void FooBar::b() {
    cout << m_test;
}

The code cout << test does not yield any output, because m_test is "" instead of "Foo bar". Why is this? I thought that passing this as the 2nd argument to bind would allow me to access the same instance from b() - am I incorrect?

+4  A: 

Yes, that works. Here's the "real" version, which does in fact print "Foo bar":

#include <boost/make_shared.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>

using namespace boost;

struct FooBar {
    void a();
    void b();
    shared_ptr<thread> m_thread;
    std::string m_test;
};

void FooBar::a() {
    m_test = "Foo bar";
    m_thread = make_shared<thread>(bind(&FooBar::b, this));
}

void FooBar::b() {
    std::cout << m_test;
}

int main() {
    FooBar fb;
    fb.a();
    fb.m_thread->join();
    return 0;
}

The code cout << test does not yield any output, because m_test is ""

I suspect this is because the object was being destroyed before the thread got around to evaluating the member variable. Note the join(), it's very important.

Tim Sylvester
Excellent thanks for posting working code! And yes, I put a breakpoint in the destructor and hey presto, turns out I was using a full type for my static singleton, instead of a pointer - duh! So a new instance was being created every time I called the singleton. Fixed now, thanks again for your code.
nbolton