c++11 lambda(匿名函数)

#include <iostream>
#include <functional>
using namespace std::placeholders;
//lambda即匿名函数
int main()
{
    int a = 10;
    //当return所有的返回都是一个类型就不需要指定返回值的类型,因为编译器会自动推断
    //也可以指定返回值类型形式:[]()->int{return 1};
    //格式:[captures] (params) -> ret {Statments;}  
    auto func = [](){
        std::cout << "hheh" << std::endl;
    };

    //lambda中变量截取
    /*    [] 不截取任何变量
        [&} 截取外部作用域中所有变量,并作为引用在函数体中使用
        [=] 截取外部作用域中所有变量,并拷贝一份在函数体中使用
        [=, &foo]   截取外部作用域中所有变量,并拷贝一份在函数体中使用,但是对foo变量使用引用
        [bar]   截取bar变量并且拷贝一份在函数体重使用,同时不截取其他变量
        [this]            截取当前类中的this指针。如果已经使用了&或者=就默认添加此选项。*/
    
    //所有要在lambda中使用a需要
    auto func1 = [=](){
        std::cout << "hheh" << std::endl;
        std::cout << a << std::endl;
    };
    func1();
    getchar();
    return 0;
}

 

    for(int i = 0; i < thread_numb; ++i)
    {
        m_libevent_threads[i]->spThread.reset(new std::thread([]
        (void* arg)
        {
            auto me = (LibeventThread*) arg;
            event_base_loop(me->thread_base, 0); //线程循环派发
        }, m_libevent_threads[i]));
    }

可以传递参数

m_libevent_threads[i]
posted @ 2014-07-31 22:49  zzyoucan  阅读(791)  评论(0编辑  收藏  举报