Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c++ - Error: variable "cannot be implicitly captured because no default capture mode has been specified"

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());

but this fails to compile:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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; });

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; });

Or by mutable value:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...