C++ lambda函数,当函数参数用复制的方式捕获时,参数存放在哪里呢?
开始以为在栈里,好像不对。
带着这个疑问,写一段递归函数,将参数的地址打出来看看。
参考代码如下:
#include <stdio.h> #include <functional> void fun2( std::function<void()> 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; }
(编译环境:mingw64, 版本x64-4.8.0-release-posix-seh-rev2)
结果令人吃惊。以下为输出结果,注意捕获参数的地址,并不在程序的stack区域,
并且地址还不总是连续的。
很明显,lambda表达的复制捕获的参数,是动态分配出空间存放的。
特别关注效率或动态分配的场合,还是小心为妙。现实很骨感。
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
(转载请标明:http://www.cnblogs.com/xhawk18/)