加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

c++ lambda表达式捕获类数据成员 this

(2014-06-07 16:49:02)
标签:

it

c

lambda

c11

捕获

分类: C/Cpp

lambda表达式允许捕获局部变量,但是数据成员不是局部变量。用一种特殊的方法,你可以捕获“this”:。

using namespace std;

class Kitty {
public:
    explicit Kitty(int toys) : m_toys(toys) { }

    void meow(const vector& v) const {
        for_each(v.begin(), v.end(), [this](int n) {
            cout << "If you gave me " << n << " toys, I would have " << n + m_toys << " toys total." << endl;
        }
);
    }

private:
    int m_toys;
};

int main() {
    vector v;

    for (int i = 0; i < 3; ++i) {
        v.push_back(i);
    }

    Kitty k(5);
    k.meow(v);
}

If you gave me 0 toys, I would have 5 toys total.
If you gave me 1 toys, I would have 6 toys total.
If you gave me 2 toys, I would have 7 toys total.

当你捕获了this以后,m_toys就可以使用了,它隐式的表示this->m_toys,你也可以显示的说明this->m_toys。(在lambda表达式中,只有捕获了this后才可以使用它,你永远无法得到lambda表达式本身的this指针)

你也可以隐式的捕获this:


using namespace std;

class Kitty {
public:
    explicit Kitty(int toys) : m_toys(toys) { }

    void meow(const vector& v) const {
        for_each(v.begin(), v.end(), [=](int n) {
            cout << "If you gave me " << n << " toys, I would have " << n + m_toys << " toys total." << endl;
        }
);
    }

private:
    int m_toys;
};

int main() {
    vector v;

    for (int i = 0; i < 3; ++i) {
        v.push_back(i);
    }

    Kitty k(5);
    k.meow(v);
}

C:\Temp>cl /EHsc /nologo /W4 implicitmemberkitty.cpp > NUL && implicitmemberkitty
If you gave me 0 toys, I would have 5 toys total.
If you gave me 1 toys, I would have 6 toys total.
If you gave me 2 toys, I would have 7 toys total.

你也可以使用“[&]”,但是它不会影响this的捕获方式(永远按值传递)。“[&this]”是不允许的。


上面代码不是自己的,今天做到c++ primer(第五版) 13.43 遇到了问题,查了查,然后记下来了

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有