C ++理解lambda可变

时间:2013-12-04 06:00:57

标签: c++ c++11 lambda mutable

好的,正如there解释的那样,可变规范可用于修改外部变量的副本,并且不会修改原始变量(不是副本)。

所以我接下来尝试了:

const int elementCount = 4;
    std::vector<int> v(elementCount, 1);
    int x = 1;
    int y = 1;
    cout << "x 1 = " << x << endl;
    cout << "y 1 = " << y << endl;
    std::generate_n(v.begin() + 2, elementCount - 2, [=]() mutable throw() -> int {

        // Generate current value.
        int n = x + y;
        cout << "x 2 = " << x << endl;
        cout << "y 2 = " << y << endl;

        // Update previous two values.
        x = y;
        y = n;
        cout << "x 3 = " << x << endl;
        cout << "y 3 = " << y << endl;
        return n;
    });
    cout << "x 4 = " << x << endl;
    cout << "y 4 = " << y << endl;

记录:

x 1 = 1
y 1 = 1
x 2 = 1
y 2 = 1
x 3 = 1
y 3 = 2
x 2 = 1
y 2 = 2
x 3 = 2
y 3 = 3
x 4 = 1
y 4 = 1

我想知道复制变量的值是从调用到调用保存的。我假设创建了lambda对象的一些实例变量。并且修改了实例变量,这就是为什么复制变量的值从调用到保存的保存。

为了检查我的假设,我做了以下事情:

 const int elementCount = 4;
    std::vector<int> v(elementCount, 1);

    int x = 1;
    int y = 1;
    cout << "x 1 = " << x << endl;
    cout << "y 1 = " << y << endl;
    // Assign each element in the vector to the sum of the
    // previous two elements.

    auto lambda_gen = [=]() mutable throw() -> int {

        // Generate current value.
        int n = x + y;
        cout << "x 2 = " << x << endl;
        cout << "y 2 = " << y << endl;

        // Update previous two values.
        x = y;
        y = n;
        cout << "x 3 = " << x << endl;
        cout << "y 3 = " << y << endl;
        return n;
    };

    std::generate_n(v.begin() + 2, elementCount - 2, lambda_gen);
    cout << "second calls group" << endl;
    std::generate_n(v.begin() + 2, elementCount - 2, lambda_gen);
    cout << "x 4 = " << x << endl;
    cout << "y 4 = " << y << endl;

所以,只有一个lambda_gen实例,我认为副本x和y的值 可以从第一次调用std :: generate_n到第二次保存。 但输出是:

x 1 = 1
y 1 = 1
x 2 = 1
y 2 = 1
x 3 = 1
y 3 = 2
x 2 = 1
y 2 = 2
x 3 = 2
y 3 = 3
second calls group
x 2 = 1
y 2 = 1
x 3 = 1
y 3 = 2
x 2 = 1
y 2 = 2
x 3 = 2
y 3 = 3
x 4 = 1
y 4 = 1

从通话到通话都没有保存!为什么?为什么在std :: generate_n内部调用保存调用,当我两次调用std :: generate_n时没有保存? Pelase帮助我, 如何mutable规范在lambdas中起作用?

0 个答案:

没有答案