Re: what is the semantic of a ref to a function or functor
tomgee wrote:
int main()
{
factorial f(10);
boost::thread thrd(boost::ref(f));// boost::thread thrd(f) would
result in f.result()==0
thrd.join();
std::cout << "10! = " << f.result() << std::endl;
}
I happen to find that if I remove boost::ref from boost::thread
thrd(boost::ref(f)); the result would result in f.result() changing
from a correct value(3628800) to 0.
This is the essence of the problem (I'm pretending that calculate is
public, which doesn't affect the logic):
void evaluate(factorial copy_of_f)
{
copy_of_f.calculate();
}
int main()
{
factorial f(10);
evaluate(f);
cout << f.result() << '\n';
return 0;
}
The argument to evaluate is copied at the point of the call, and
copy_of_f.calculate() is called on that copy, not the original one. Back
in main, f.result() is called on the original version of f, which hasn't
been changed.
If you change the function evaluate to take its argument by reference,
the call to calculate gets applied to the original version of f, and
everything works as expected.
Back in your original code, thread's constructor takes the callable
object by value. When you initialize the thread object directly
with thrd(f) you end up running your thread from a copy of f, just like
the version of evaluate above. ref(f), on the other hand, returns an
object that holds a reference to f. That object has a function call
operator that hands off to f's function call operator. So, in essence,
it passes f by reference, even though the constructor takes its argument
by value. And just like the simplified example, passing by reference is
what you need.
--
-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]