错误:变量“无法隐式捕获,因为未指定默认捕获模式"

2021-12-23 00:00:00 lambda c++ c++11

我正在尝试遵循这个例子使用带有 remove_if 的 lambda.这是我的尝试:

I am trying to follow this example to use a lambda with remove_if. Here is my attempt:

int flagId = _ChildToRemove->getId();
auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(), 
        [](Flag& device) { 
            return device.getId() == flagId; 
        });

m_FinalFlagsVec.erase(new_end, m_FinalFlagsVec.end());

但这无法编译:

error C3493: 'flagId' cannot be implicitly captured because no default capture mode has been specified

如何在 lambda 表达式中包含外部参数 flagId?

How can I include the outside parameter, flagId, in the lambda expression?

推荐答案

您必须指定要捕获的 flagId.这就是 [] 部分的用途.现在它没有捕获任何东西.您可以按值或按引用捕获(更多信息).类似的东西:

You must specify flagId to be captured. That is what the [] part is for. Right now it doesn't capture anything. You can capture (more info) by value or by reference. Something like:

auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
        [&flagId](Flag& device)
    { return device.getId() == flagId; });

通过引用捕获.如果你想通过 const 值捕获,你可以这样做:

Which captures by reference. If you want to capture by const value, you can do this:

auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
        [flagId](Flag& device)
    { return device.getId() == flagId; });

或者通过可变值:

auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
        [flagId](Flag& device) mutable
    { return device.getId() == flagId; });

遗憾的是,没有直接的方法可以通过常量引用进行捕获.我个人只会声明一个临时的 const ref 并通过 ref 捕获它:

Sadly there is no straightforward way to capture by const reference. I personally would just declare a temporary const ref and capture that by ref:

const auto& tmp = flagId;
auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
            [&tmp](Flag& device)
        { return device.getId() == tmp; }); //tmp is immutable

相关文章