C++閉包,一樣很簡單

來源:互聯網
上載者:User

標籤:vector   UI   c++   uil   pretty   visual   對象   矛盾   sts   

引用百度上對閉包的定義:閉包是指可以包含自由(未綁定到特定對象)變數的代碼塊;這些變數不是在這個代碼塊內或者任何全域上下文中定義的,而是在定義代碼塊的環境中定義(局部變數)。“閉包” 一詞來源於以下兩者的結合:要執行的代碼塊(由於自由變數被包含在代碼塊中,這些自由變數以及它們引用的對象沒有被釋放)和為自由變數提供綁定的計算環境(範圍)。在PHP、Scala、Scheme、Common Lisp、Smalltalk、Groovy、JavaScript、Ruby、 Python、Go、Lua、objective c、swift 以及Java(Java8及以上)等語言中都能找到對閉包不同程度的支援。 
那,C++難道不支援閉包嗎? 非也!

C++閉包

有了C++14的支援,實現閉包還是輕而易舉!

#include <functional>#include <iostream>#include <vector>using namespace std;auto foo(int bar){    const char t = ‘A‘ + bar;    return [=](int b)->char {        const char res = t + b;        return res;         };}int main(int argc, char * argv[]){    const int tests = 8;    //產生8個閉包    vector<function<char(int)> > vec_closures;    for (int i = 0; i < tests; ++i)        vec_closures.push_back(foo(i));    //多線程集中調用#pragma omp parallel for    for (int i = 0; i < tests; ++i)    {        const char res = vec_closures[i](i + 1);        cout <<  res;    }    cout << endl;    //單線程集中調用    for (int i = 0; i < tests; ++i)    {        const char res = vec_closures[i](i + 1);        cout << res;    }    cout << endl;    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

上面的代碼中,在函數foo裡建立了一個調用,使用值捕獲局部變數。到主函數裡,分別以多線程和單線程的模式調用10次。輸出:

BFDJLNHPBDFHJLNP請按任意鍵繼續. . .
  • 1
  • 2
  • 3

不過注意了,這裡的lambada運算式採用的是[=]值捕獲。如果採用引用捕獲,會如何呢?

auto foo(int bar){    const char t = ‘A‘ + bar;    return [&](int b)->char {        const char res = t + b;        return res;         };}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

輸出亂碼。 
究其原因,應該是採用引用捕獲時,由於函數foo並不在當前堆棧的 
執行鏈上,對局部變數t的引用也就非法了。我們看看堆棧:

>   cpp_closure.exe!foo::__l2::<lambda>(int b) 行 10 C++    cpp_closure.exe!std::_Invoker_functor::_Call<char <lambda>(int) &,int>(foo::__l2::char <lambda>(int) & _Obj, int && <_Args_0>) 行 1534   C++    cpp_closure.exe!std::invoke<char <lambda>(int) &,int>(foo::__l2::char <lambda>(int) & _Obj, int && <_Args_0>) 行 1534    C++    cpp_closure.exe!std::_Invoker_ret<char,0>::_Call<char <lambda>(int) &,int>(foo::__l2::char <lambda>(int) & <_Vals_0>, int && <_Vals_1>) 行 1569  C++    cpp_closure.exe!std::_Func_impl<char <lambda>(int),std::allocator<int>,char,int>::_Do_call(int && <_Args_0>) 行 211  C++    cpp_closure.exe!std::_Func_class<char,int>::operator()(int <_Args_0>) 行 277 C++    cpp_closure.exe!main$omp$1() 行 25   C++
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

裡面就沒有對函數 foo的壓棧記錄。

*編譯器:Microsoft Visual Studio 2017

實現一個計數器

由於C++不支援命名函數的嵌套定義,使得實作類別似JS計數器的閉包用法無法實現。但也不代表完全無法進行。比如下面的玩法:

#include <functional>#include <iostream>#include <vector>#include <unordered_map>#include <string>#include <memory>using namespace std;auto gounter(int initial){    shared_ptr<int> pct(new int{ initial });    unordered_map<string, function<int()> > functions;    functions["reset"] = [=]()->int {        *pct = initial;        return *pct;    };    functions["next"] = [=]()->int {        return (*pct)++;    };    return functions;}int main(int argc, char * argv[]){    auto counter_a = gounter(10);    auto counter_b = gounter(100);    cout << counter_a["next"]()<<endl;    cout << counter_a["next"]() << endl;    cout << counter_b["next"]() << endl;    cout << counter_b["next"]() << endl;    counter_a["reset"]();    cout << counter_a["next"]() << endl;    cout << counter_b["next"]() << endl;    return 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

輸出:

101110010110102
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
局限

C++為靜態語言,使用任何手段類比動態功能,都意味著效能損失。一味的追求文法方便,與效能上的折中是矛盾的。當然了,這也是城會玩的樂趣所在!

 

http://blog.csdn.net/goldenhawking/article/details/70589476

C++閉包,一樣很簡單

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.