为什么C ++ 11的lambda需要“可变"变量?默认情况下,按值捕获关键字? [英] Why does C++11's lambda require "mutable" keyword for capture-by-value, by default?

查看:54
本文介绍了为什么C ++ 11的lambda需要“可变"变量?默认情况下,按值捕获关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短示例:

#include <iostream>

int main()
{
    int n;
    [&](){n = 10;}();             // OK
    [=]() mutable {n = 20;}();    // OK
    // [=](){n = 10;}();          // Error: a by-value capture cannot be modified in a non-mutable lambda
    std::cout << n << "\n";       // "10"
}

问题:为什么我们需要mutable关键字?它与传递给命名函数的传统参数完全不同.背后的原因是什么?

The question: Why do we need the mutable keyword? It's quite different from traditional parameter passing to named functions. What's the rationale behind?

我的印象是按值捕获的全部要点是允许用户更改临时值-否则,使用按引用捕获几乎总是更好,不是吗?

I was under the impression that the whole point of capture-by-value is to allow the user to change the temporary -- otherwise I'm almost always better off using capture-by-reference, aren't I?

有什么启示吗?

(顺便说一下,我正在使用MSVC2010.AFAIK应该是标准的)

(I'm using MSVC2010 by the way. AFAIK this should be standard)

推荐答案

它需要mutable,因为默认情况下,每次调用函数对象都应产生相同的结果.这实际上是面向对象的函数和使用全局变量的函数之间的区别.

It requires mutable because by default, a function object should produce the same result every time it's called. This is the difference between an object orientated function and a function using a global variable, effectively.

这篇关于为什么C ++ 11的lambda需要“可变"变量?默认情况下,按值捕获关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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