Re: Equivalent of boost::val?
Alberto Ganesh Barbati ha scritto:
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.
Oops, I seems that I answered the exact opposite of what you requested.
I apologize for the noise.
The correct answer is that you don't need any such thing as boost::val,
because
boost::bind(foo, i);
always stores i by value, regardless of foo() taking an int or const
int& parameter. See http://boost.org/libs/bind/bind.html#Purpose for
reference, in particular, the sentence:
"For example, in the following code:
int i = 5;
bind(f, i, _1);
a copy of the value of i is stored into the function object. boost::ref
and boost::cref can be used to make the function object store a
reference to an object, rather than a copy"
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]