6

c++ lambda 表达式里 为什么值捕获的局部变量无法修改?

 2 years ago
source link: https://www.v2ex.com/t/838315
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  C++

c++ lambda 表达式里 为什么值捕获的局部变量无法修改?

  amiwrong123 · 7 小时 4 分钟前 · 587 次点击
[&i] ( ) { std::cout << i; }

// is equivalent to

struct anonymous
{
    int &m_i;
    anonymous(int &i) : m_i(i) {}
    inline auto operator()() const
    {
        std::cout << m_i;
    }
};

首先我知道,一个如上的 lambda 表达式,其实相当于生成了一个如上匿名 struct 的实例 a ,运行 lambda 表达式时,其实就相当于执行 a().

int main()
{
    int v1 = 42;
    auto f = [v1]() {return ++v1; };//值捕获
    v1 = 0;
    auto j = f(); //j 为 43

}

但是如上的代码却无法通过编译,除非你加上 mutable 。所以我是不是可以认为,如上的 lambda 表达式,是不是实际生成了如下的 struct ?

struct anonymous
{
    int m_i;
    anonymous(int i) : m_i(i) {}
    inline auto operator()() const//如果你加上 mutable ,这里的 const 才会去掉
    {
        m_i++;
    }
};

另外,c++ lambda 表达式是不是都可以认为 它的等价情况,就是生成了一个 重载了 operator()的匿名结构体的实例?如果不是的话,请帮忙举一个反例。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK