Lambda捕获和成员变量 [英] Lambda captures and member variables

查看:116
本文介绍了Lambda捕获和成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看 Herb Sutter的talk 在C ++和Beyond 2012的并发会议上,他谈到了创建一个非阻塞包装类,他调用 concurrent< T> 函数。

I was watching Herb Sutter's talk at the C++ and Beyond 2012 conference on Concurrency and he talks about creating a non-blocking wrapper class, which he calls concurrent<T>, with C++11 functions.

他的实现相当简单(除了需要一个 concurrent_queue ,如存在于Microsoft的PPL中) :

His implementation is fairly simple (aside from needing a concurrent_queue such as that which exists in Microsoft's PPL):

template <class T>
class concurrent {
private:
    mutable T t;
    mutable concurrent_queue<std::function<void()>> q;
    bool done = false;
    std::thread thread;

public:
    concurrent( T t_ = T{} ) : t{t_}, thread{ [=]{ while( !done ) q.pop()(); }} {}

    ~concurrent() { q.push( [=]{ done = true; } ); thread.join(); }

    template <typename F>
    void operator()( F f ) const { q.push( [=]{ f(t); } ); }

};

这看起来很简单,但是我很困惑为什么他捕获了成员变量 done q 按值而不是引用?我的理解是,如果他们被捕获的价值,那么他们将被复制到线程,因此当队列更新时,工作线程将不会收到更新?

This seems simple enough, however, I'm confused as to why he has captured the member variables done and q by value instead of by reference? My understanding is that if they are captured by value then they will be copied to the thread and thus when the queue is updated the worker thread will not receive the updates?

我误解了lambda捕获对类成员变量的工作吗?没有人在视频的评论或在谈话期间说任何东西,所以我假设我的理解是错误的,在这种情况下,有人可以澄清吗?

Have I misunderstood how lambda captures work with regards to class member variables? No one said anything in the comments to the video or during the talk so I am assuming that my understanding is faulty, in which case could someone please clarify?

推荐答案

成员变量可以永远不会被捕获的值。被值捕获的是隐藏的这个指针用于访问它们。因此,它通过值捕获指针,这意味着它通过引用捕获此对象(及其成员)。

Member variables can never be captured by value. What's being captured by value is the implicit this pointer used to access them. Therefore, it's capturing a pointer by value, which means it captures this object (and its members) by reference.

这篇关于Lambda捕获和成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆