views:

86

answers:

2

Hi All,

Could you tell mw what is the problem with the below boost::thread program

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

boost::mutex mutex;

class A
{
public:
A() : a(0) {}

void operator()()
{
          boost::mutex::scoped_lock lock(mutex);

}
private:
int a;

};

int main()
{
    boost::thread thr1(A());
    boost::thread thr2(A());
    thr1.join();
    thr2.join();

}

I get the error message: error: request for member 'join' in 'thr1', which is of non-class type 'boost::thread()(A ()())' BoostThread2.cpp:30: error: request for member 'join' in 'thr2', which is of non-class type 'boost::thread ()(A ()())'

+2  A: 
Marcelo Cantos
Well, then isn't A() - a temporary instance of class A ?
Eternal Learner
I've amended my answer to (I hope) make it clear why this happens.
Marcelo Cantos
Thanks, It helps..
Eternal Learner
+2  A: 

You have stumbled on something wonderfully known as the most vexing parse. The quickest way to fix that is to add an extra set of parentheses:

boost::thread thr1((A()));

You can also introduce a temporary:

A tmp1;
boost::thread thr1(tmp1);

In the most vexing parse, what you think is generating a temporary is parsed as if it's a function taking no parameters. It then threads thr1 as a prototype to a function that takes a single parameter (which is the function mentioned previously) and returning a boost::thread.

R Samuel Klatchko
Yeah , I just did that and it works fine, i just could not get why it behaves like that.
Eternal Learner
@EternalLearner - I just added a short summary of what is happening. If you want a more, search for "most vexing parse" and you'll find plenty of more detailed explanations.
R Samuel Klatchko
Thanks, I did a quick search on that. It helps..
Eternal Learner