In C++11 lambda syntax, heap-allocated closures?

后端 未结 2 1794
醉酒成梦
醉酒成梦 2021-02-07 02:48

C++11 lambdas are great!

But one thing is missing, which is how to safely deal with mutable data.

The following will give bad counts after the first count:

2条回答
  •  庸人自扰
    2021-02-07 03:23

    Here's my testing code. It uses recursive function to compare the address of lambda parameters with other stack based variables.

    #include  
    #include  
    
    void fun2( std::function callback ) { 
        (callback)(); 
    } 
    
    void fun1(int n) { 
        if(n <= 0) return; 
        printf("stack address = %p, ", &n); 
    
        fun2([n]() { 
            printf("capture address = %p\n", &n); 
            fun1(n - 1); 
        }); 
    } 
    
    int main() { 
        fun1(200); 
        return 0; 
    }
    

    Compile the code with mingw64 and runs on Win7, it output

    stack address = 000000000022F1E0, capture address = 00000000002F6D20
    stack address = 000000000022F0C0, capture address = 00000000002F6D40
    stack address = 000000000022EFA0, capture address = 00000000002F6D60
    stack address = 000000000022EE80, capture address = 00000000002F6D80
    stack address = 000000000022ED60, capture address = 00000000002F6DA0
    stack address = 000000000022EC40, capture address = 00000000002F6DC0
    stack address = 000000000022EB20, capture address = 00000000007A7810
    stack address = 000000000022EA00, capture address = 00000000007A7820
    stack address = 000000000022E8E0, capture address = 00000000007A7830
    stack address = 000000000022E7C0, capture address = 00000000007A7840
    

    It's obvious that the captured parameter is not located on stack area, and the address of captured parameters is not continuous.

    So I believe that some compilers may use dynamical memory allocation to
    capture lambda parameters.

提交回复
热议问题