Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

example code of escaping lambdas

Tags:

c++

c++11

lambda

I watched the cool clip: http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2011-C11-Panel-Scott-Meyers-Andrei-Alexandrescu-and-Herb-Sutter
and there Andrei(54:00) talks about escaping lambdas that take references to locals. In general I think I get the idea of the problem, but I'm not sure that I really get it, so I would like to go through example. So is there any simple example of this?

like image 719
NoSenseEtAl Avatar asked Jun 08 '26 15:06

NoSenseEtAl


1 Answers

Here's a simple example:

std::function<int()> f() {
    int local;
    return [&]() { return local; }
}

The local variable is captured by reference, and then the lambda is returned. Calling the returned function later on will use the reference, which is now invalid and thus invokes undefined behaviour. This seems like a simple enough case for a compiler to issue a warning for. I expect we'll be seeing it in the future.

Here's a more complex example:

std::function<int()> f() {
    int local;
    return g(local);
}

std::function<int()> g(int const& param) {
    return [&]() { return param; }
}

The function g could be defined in another translation unit, and this would hurt the ability of a compiler to issue a warning.

like image 113
R. Martinho Fernandes Avatar answered Jun 11 '26 03:06

R. Martinho Fernandes