C++ 错误:变量“无法隐式捕获,因为未指定默认捕获模式”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30217956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: variable "cannot be implicitly captured because no default capture mode has been specified"
提问by user63898
I am trying to follow this exampleto use a lambda with remove_if
. Here is my attempt:
我正在尝试按照此示例将 lambda 与remove_if
. 这是我的尝试:
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?
如何flagId
在 lambda 表达式中包含外部参数 , ?
回答by AndyG
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:
您必须指定flagId
被捕获。这就是[]
零件的用途。现在它没有捕获任何东西。您可以按值或按引用捕获(更多信息)。就像是:
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:
通过引用捕获。如果你想通过 const 值捕获,你可以这样做:
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 ref 并通过 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