
On Fri, Nov 18, 2011 at 3:20 PM, Lorenzo Caminiti <lorcaminiti@gmail.com>wrote:
On Fri, Nov 18, 2011 at 1:31 PM, Jeffrey Lee Hellrung, Jr. <jeffrey.hellrung@gmail.com> wrote:
On Fri, Nov 18, 2011 at 1:44 AM, Lorenzo Caminiti <lorcaminiti@gmail.com wrote:
On Wed, Nov 16, 2011 at 10:24 AM, Lorenzo Caminiti
[...]
boost::function<void (int&)> counter() { int delta = 2; void BOOST_CLOSURE(int& x, bind delta) {
Of course, you meant "bind x" or "int x" here instead of "int& x", right?
No, I meant int& x. In this case the local function accepts one parameter of type int& and it is closed over a copy of value of the local variable delta. Given that none of the variables is bound by reference (the only reference is a function parameter and not a bound variable), such a closure can be safely returned to another scope and executed outside the local scope (within main in this case). When main will execute the closure, it will have to pass the one parameter x (see inc(x) below).
x += delta; std::cout << "x = " << x << std::endl; } BOOST_CLOSURE_END(increment) return increment; }
int main() { int x = 1; boost::function<void (int&)> inc = counter(); inc(x); // undefined behaviour now but it should work... return 0; }
[...]
Ack, right. I wasn't paying attention and didn't notice that you had moved the x variable to main relative to the preceding (snipped) example. - Jeff