what is the semantic of a ref to a function or functor
I am reading a piece of sample code from boost.thread, which is copied
below in full:
// Copyright (C) 2001-2003
// William E. Kempf
#include <boost/thread/thread.hpp>
#include <boost/ref.hpp>
#include <iostream>
class factorial
{
public:
factorial(int x) : x(x), res(0) { }
void operator()() { res = calculate(x); }
int result() const { return res; }
private:
int calculate(int x) { return x <= 1 ? 1 : x * calculate(x-1); }
private:
int x;
int res;
};
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.
While I tried to understand why, I realized I never really learned what
a reference to a function or functor is. In the semantics of pure
function pointers, there's no difference between passing f or &f as
a parameter. I know references are not pointers. however, can any one
please kindly explain
the difference in this case? Thanks.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]