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

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

问题描述

简短示例:

  #include< iostream& 

int main()
{
int n;
[&](){n = 10;}(); // OK
[=]()mutable {n = 20;}(); // OK
// [=](){n = 10;}(); //错误:无法在不可变的lambda中修改旁边值捕获
std :: cout<< n<< \\\
; //10
}

问题:为什么我们需要 mutable 关键字?它与传统的参数传递给命名函数非常不同。后面有什么理由?



我的印象是,捕获值的整个点是允许用户更改临时 - 否则我的

任何启示?



我使用MSVC2010的方式。AFAIK这应该是标准的)

解决方案

它需要 mutable 因为默认情况下,一个函数对象应该在每次调用时产生相同的结果。这是面向对象函数和使用全局变量的函数之间的区别。


Short example:

#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"
}

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?

Any enlightenments?

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

解决方案

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 ++ 0x的lambda需要“可变”默认情况下,按值捕获的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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