请参阅下面的代码。正确的输出是“10 20 30”,但在Release中构建它的“0 0 0”。为什么会出现这种情况?
std::vector<int> inValues = {1, 2, 3};
std::vector<int> outValues(inValues.size());
static const int mag = 10;
std::transform(inValues.cbegin(), inValues.cend(), outValues.begin(),
[](const auto value){
return value * mag;
});
for (const auto value: outValues)
std::cout << value << " ";
如果变量在函数内的任何地方被提及,或者在全局范围内声明,则一切都会按预期工作。
最佳答案
说到捕获 lambda 中的变量,http://en.cppreference.com/w/cpp/language/lambda#Explanation说:
A variable can be used without being captured if it does not have automatic storage duration (i.e. it is not a local variable or it is static or thread local)
您的变量是“静态本地”,因此应该自动捕获。
此外Microsoft gives this example of using a local static storage element :
void fillVector(vector<int>& v)
{
// A local static variable.
static int nextValue = 1;
// The lambda expression that appears in the following call to
// the generate function modifies and uses the local static
// variable nextValue.
generate(v.begin(), v.end(), [] { return nextValue++; });
//WARNING: this is not thread-safe and is shown for illustration only
}
这确实按预期工作,尽管您的示例没有。
这是 visual-studio-2015 bug。我可以报告它已在 visual-studio-2017 中清除。 。因此,虽然您可以随意将此问题报告为错误,但我建议您升级到 Visual Studio 2017。如果您确实选择报告它,我鼓励您在此处链接错误报告。
关于c++ - 如果仅在 lambda 中使用,则局部静态变量不会在发布版本中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46958919/