在 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.
这是怎么回事?
最佳答案
您的捕获规范表明您希望通过引用捕获所有局部变量,但您希望通过值捕获的 tableString
和 trPosVec
除外。如果这两个变量是你想要捕获的唯一变量,并且你想通过引用捕获它们,你应该使用捕获表达式,[&tableString, &trPosVec]
,或者简单地通过引用捕获所有局部变量, [&]
。
关于c++ - Visual C++ 2012 似乎不尊重 lambda 中的默认捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18420647/