Visual C++ 2012 似乎不尊重 lambda 中的默认捕获
Visual C++ 2012 doesn't seem to respect default capture in lambdas
在MSVC 2012中:
const std::string tableString;
std::vector<size_t> trPosVec;
// other stuff...
std::for_each(trIterator, endIterator,
[&, tableString, trPosVec](const boost::match_results<std::string::const_iterator>& matches){
trPosVec.push_back(std::distance(tableString.begin(), matches[0].second));
}
);
此代码给出工具提示错误:
Error: no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=size_t, _Alloc=std::allocator<char32_t>]" matches the argument list and object (the object has type qualifiers that prevent a match)
argument types are: (ptrdiff_t)
object type is: const std::vector<size_t, std::allocator<char32_t>>
我认为这意味着它正在按值捕获CCD_ 1。当我明确指定捕获模式[&tableString, &trPosVec]
时,它工作得很好。如果我尝试像[&, tableString, &trPosVec]
那样双重指定,它会给出Error: explicit capture matches default.
这里发生了什么?
您的捕获规范指示您希望通过引用捕获所有局部变量,但tableString
和trPosVec
除外,它们是您希望通过值捕获的。如果这两个变量是您想要捕获的唯一变量,并且您想要通过引用捕获它们,那么您应该使用捕获表达式[&tableString, &trPosVec]
,或者简单地通过引用捕获所有局部变量[&]
。
相关文章:
- 在未显式传递参数时默认使用 lambda 的用户输入
- 处于默认参数位置的 Lambda 无法访问好友成员。这是编译器错误吗?
- 变量不能在 lambda 中隐式捕获,并且没有使用 switch 语句指定捕获默认值
- 是否可以使用默认泛型参数在C++中定义 lambda?
- C++14 及更高版本是否允许 Lambda 函数的默认参数?如果是这样,怎么办?
- 使用默认参数从 lambda 调用最少数量的参数
- 可以使用默认参数复制包含 lambda 的 std::函数吗?
- lambda 的默认捕获是什么?
- 默认引用与命名的 lambda 捕获
- 在默认初始值设定项中使用 lambda 与使用成员函数
- 如何编写具有默认参数的lambda的通用函数
- 未评估上下文中的默认模板参数和 lambda:错误还是功能?
- 默认模板类Lambda
- C++14 lambda 的默认参数类型推导,具体取决于前面的参数
- 如何将 lambda 用作模板参数,C++ 中的默认值
- 默认函数对象值作为要使用lambda调用的函数参数
- 模板,lambda作为每个实例化的唯一默认参数
- 当另一个调用 lambda 使用默认捕获时,lambda 的闭包可能会被破坏吗?
- 将具有默认参数的lambda函数复制到变量
- 在C++11中使用lambda默认值捕获或引用捕获的缺点