Lambda Capture by Value强制所有作用域对象为常量
Lambda Capture by Value forces all scoped object to const
我本来打算用C++编写一个记忆模式,结果采用了以下方法
std::function<int(int)> Memoize(std::function<int(int)> fn)
{
std::map<int, int> memo;
std::function<int(int)> helper = [=](int pos)
{
if (memo.count(pos) == 0)
{
memo[pos] = fn(pos);
}
return memo[pos];
};
return helper;
}
奇怪的是,我的编译器VS 2012拒绝编译,出现以下错误
1>Source1.cpp(24): error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>' (or there is no acceptable conversion)
在我看来,编译器故意将所有按值捕获的内容作为const对象。我找不到任何关于这种行为的文献。
有人能帮助我了解这里可能发生的事情吗?
Lambdas的行为或多或少类似于函数对象;像函数对象一样,它们有一个函数调用运算符,即operator()
。对于非mutable
lambdas,此函数为const
:
[expr.prim.lambda]
5非泛型lambda表达式的闭包类型具有公共内联函数调用运算符[…]此函数调用运算符或运算符模板被声明为
const
(9.3.1)当且仅当lambda表达式的参数声明子句后面不跟mutable
。
因为副本捕获的实体的行为就像它们是lambda:的成员变量
15[…]对于通过复制捕获的每个实体,在闭包类型中声明一个未命名的非静态数据成员。
而非mutable
成员不能在const
成员函数([class.this]/1,[dcl.type.cv]/4)内修改,如果要修改捕获的实体,则必须声明mutable
lambda。
就目前情况来看,你的lambda看起来是这样的:
class Helper
{
public:
int operator()(int) const;
private:
std::map<int, int> memo;
std::function<int(int)> fn;
};
您可以将mutable
lambda视为具有非const
operator()
,在您的情况下,lambda可以定义如下:
std::function<int(int)> helper = [=](int pos) mutable
// etc
为了使lambda函数成为常量,您需要添加mutable
关键字:
std::function<int(int)> Memoize(std::function<int(int)> fn)
{
std::map<int, int> memo;
std::function<int(int)> helper = [=](int pos) mutable // <== HERE!!
{
if (memo.count(0) == 0)
{
memo[pos] = fn(pos);
}
return memo[pos];
};
return helper;
}
相关文章:
- 在构造函数中输入对象时C++类成员作用域
- 混合指向已分配对象和作用域对象的指针
- 在一个作用域中推送五个对象指针,然后检查对象的布尔值是否为 false,会给出错误
- 类的堆分配对象是否在其作用域之后但在 C++ 中调用其析构函数之前处于活动状态
- 在c++中,全局作用域中只允许"表达式"初始化全局对象.我在哪里可以在标准中找到这个
- 无法访问类作用域中的对象
- 在提升作用域出口中调用对象函数
- 用LD_PRELOAD和C++中的全局作用域对象加载堆分析器
- 将对象的属性传递到方法时出现作用域问题.(opencv相关)
- 在调用函数的作用域中构造返回的对象
- 本地对象的作用域
- 函数作用域的静态非 Pod 对象初始化
- C++有必要删除主作用域末尾动态分配的对象
- 超出作用域在c++对象中意味着什么
- Lambda Capture by Value强制所有作用域对象为常量
- 当类没有析构函数时,智能指针或作用域指针会删除对象吗
- 未在作用域中声明指针对象
- 当shared_ptr的实例仍在作用域中时,共享指针的对象被删除
- 对临时对象的常量引用在函数作用域(生存期)后被破坏
- 堆上的对象何时超出作用域?