(C++0x) Use of the function<> template

Consider this piece of code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <functional>

std::function<void (int)> fff;

void fun1() {
    int val;
    fff=[&val](int i) { val = i; };
}

void fun2() {
    fff(20);
}

int main()
{
    fun1();
    fun2();
}

In fun1 the function fff is set up to refer to the local variable val. But when fff is called in fun2, val no longer exists.

I presume that this will mean that fff will modify a random location in memory with potential disastrous results. Right?

So obviously capturing val by reference is an unsafe thing to do.

But what if val is captured by value:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <functional>

std::function<void (int)> fff;

void fun1() {
    int val=42;
    fff=[val](int i) { std::cout << val+i; };
}

void fun2() {
    fff(20);
}

int main()
{
    fun1();
    fun2();
}

Whould this be safe?
closed account (S6k9GNh0)
http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions

I would suspect that it mocks parameters of functions in that you can assume that it's safe. However, I didn't read directly from the standard on this... You might want to look directly at it for a sure answer.
Last edited on
It is safe because val is captured by value so a copy of val exists in fff after the assignement at line 8, there will be no dereference in the call at line 12.
Topic archived. No new replies allowed.