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

Visual C++ 2012 doesn't seem to respect default capture in lambdas

本文关键字:lambda 默认 2012 C++ Visual      更新时间:2023-10-16

在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.这里发生了什么?

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