c++ - 如果仅在 lambda 中使用,则局部静态变量不会在发布版本中初始化

标签 c++ visual-studio-2015 lambda

请参阅下面的代码。正确的输出是“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  
}  

这确实按预期工作,尽管您的示例没有。

这是 bug。我可以报告它已在 中清除。 。因此,虽然您可以随意将此问题报告为错误,但我建议您升级到 Visual Studio 2017。如果您确实选择报告它,我鼓励您在此处链接错误报告。

关于c++ - 如果仅在 lambda 中使用,则局部静态变量不会在发布版本中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46958919/

相关文章:

c++ - 为什么 map 上的 std::for_each 会调用复制构造函数?

c++ - 级联 NavigationPane : connect to an object signal into another qml file

c++ - 平等的定义

c++ - Visual Studio 中的 "Pointer to reference"错误未按发生位置的文件名显示

visual-studio-2012 - Visual Studio 2015-2019 : How do I bring back the old find dialog from VS 2010?

java - ThrowableCaptor 可在 Eclipse 中运行,但不能在 Netbeans 中运行

C++ 在列表中查找 double

c++ - 链接 Bullet Physics Library 的问题(与 brew 一起安装)

.net - MSBuild 错误 : "Could not resolve this reference. Could not locate the assembly..."

haskell - 如何结合二元和一元函数来获得折叠的阶跃函数?