c++ - Visual C++ 2012 似乎不尊重 lambda 中的默认捕获

标签 c++ visual-c++ c++11 lambda

在 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>>

我的意思是它按值捕获 trPosVec。当我明确指定捕获模式 [&tableString, &trPosVec] 时,它工作正常。如果我尝试像 [&, tableString, &trPosVec] 这样的双重指定,它会给出 Error: explicit capture matches default. 这是怎么回事?

最佳答案

您的捕获规范表明您希望通过引用捕获所有局部变量,但您希望通过值捕获的 tableStringtrPosVec 除外。如果这两个变量是你想要捕获的唯一变量,并且你想通过引用捕获它们,你应该使用捕获表达式,[&tableString, &trPosVec],或者简单地通过引用捕获所有局部变量, [&]

关于c++ - Visual C++ 2012 似乎不尊重 lambda 中的默认捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18420647/

相关文章:

c++ - 编译时的不同(空)结果

c++ - IAR C/C++ 比较运算符行为

visual-studio - Visual C++ 命令行编译器 (CL.EXE) 重定向 OBJ 文件

visual-c++ - MFC:更改CEdit的颜色

c++:为什么执行回调但不执行回调定义之前的函数?

C++11 initializer_list 错误

c++ - reference_wrapper 引用原语

c++ - 给定 3D 空间中的 N 个点,如何找到包含这 N 个点的最小球体?

c++ - 让编译器根据架构选择乘法算法

C++ MFC 整数文本字段始终设置为 0?