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

jca*_*cai 1 c++ lambda visual-c++ c++11

在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));
    }
);
Run Code Online (Sandbox Code Playgroud)

此代码提供工具提示错误:

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>>
Run Code Online (Sandbox Code Playgroud)

我认为它意味着它是trPosVec按价值捕获的.当我明确指定捕获模式时,它工作正常[&tableString, &trPosVec].如果我尝试双重指定[&, tableString, &trPosVec],它会给出Error: explicit capture matches default.这里发生了什么?

Ada*_*son 6

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