c++ - Why does this C++11 lambda not behave as I expect? -


i've encountered situation challenges nascent understanding of c++ lambdas, , i've distilled down following:

#include <iostream>  void test() {     int (*func)();      func =         []()->int {             std::cerr << "func()" << std::endl;             return 0;         };      int = 0;     func =         [i]()->int {             std::cerr << "func(): i= " << << std::endl;             return 0;         }; } 

in first case, i'm assigning simple lambda function pointer, , seems work expect. i'm trying in second case provide lambda access value of i. understanding of [i]()->int {code} defines nameless function takes no arguments, returns int and, through magic of c++11 unicorns, knows current value of i. expect lambda should callable int(*)().

test.cpp: in function ‘void test()’: test.cpp:14:7: error: cannot convert ‘test()::__lambda1’ ‘int (*)()’ in assignment   func =        ^ 

it seem gcc 4.8.1 , 4.8.2 disagree assessment (4.4.1 refused discuss matter).

this seems suggest type of second lambda not assignment-compatible function pointer. don't understand why case, given that expression should callable "int(*)()".

where has understanding (or unicorns) failed me?

being invokable signature int() not mean can converted int(*)(). overloaded int operator()() invokable way.

lambdas create pretty bog standard classes such overload, wrap them in syntactic sugar. (not true, true enough)1

stateless lambdas (ones capture nothing) come bonus operator int(*)() overload (or operator signature* in general), bonus, not core lambda's being.

a function pointer is, in practice, address execution jumps when invoke function. there no room data pointer (to store state of captured variables). in theory allocate space data alongside or within execution code, many systems block marking writable pages executable security reasons, makes system impractical. there have been people have proposed kind of extension.


1 many things in c++ standard, things specified in terms of behavior not implementation. features of lambdas can duplicated implementing bog standard classes "auto-written" you, compiler doesn't have it. lambda implementations (like stack frame capture based [&] lambdas) cannot implemented within c++ language.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -