C++ lambda函數,效率也許不如想象的好

來源:互聯網
上載者:User

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 = 00000000002F6D20stack address = 000000000022F0C0, capture address = 00000000002F6D40stack address = 000000000022EFA0, capture address = 00000000002F6D60stack address = 000000000022EE80, capture address = 00000000002F6D80stack address = 000000000022ED60, capture address = 00000000002F6DA0stack address = 000000000022EC40, capture address = 00000000002F6DC0stack address = 000000000022EB20, capture address = 00000000007A7810stack address = 000000000022EA00, capture address = 00000000007A7820stack address = 000000000022E8E0, capture address = 00000000007A7830stack address = 000000000022E7C0, capture address = 00000000007A7840

(轉載請標明:http://www.cnblogs.com/xhawk18/)

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.