Std :: function crash when used in array on stack
In MS Visual C ++ 2010 SP1, this code fails:
#include "stdafx.h" #include <functional> #include <iostream> //#include <vector> int a = 0; int _tmain(int argc, _TCHAR* argv[]) { // this way it works: //std::vector<std::function<void ()>> s; //s.push_back([]() { a = 1; }); //s.push_back([]() { a = 2; int b = a; }); std::function<void ()> s[] = { []() { a = 1; }, []() { a = 2; // Problem occurs only if the following line is included. When commented out no problem occurs. int b = a; } }; int counter = 0; for (auto it = std::begin(s); it != std::end(s); ++it) { ++counter; (*it)(); std::wcout << counter << L":" << a << std::endl; } return 0; } When creating the second element of the array, it damages the first element of the array.
Is this a bug in the compiler or did I do something that is not supported in the C ++ 11 standard?
EDIT
This code works in gcc-4.5.1:
#include <functional> #include <iostream> //#include <vector> int a = 0; int main(int argc, char* argv[]) { // this way it works: //std::vector<std::function<void ()>> s; //s.push_back([]() { a = 1; }); //s.push_back([]() { a = 2; int b = a; }); std::function<void ()> s[] = { []() { a = 1; }, []() { a = 2; // Problem occurs only if the following line is included. //When commented out no problem occurs. int b = a; } }; int counter = 0; ++counter; s[0](); std::wcout << counter << L":" << a << std::endl; ++counter; s[1](); std::wcout << counter << L":" << a << std::endl; return 0; } This is a compiler error. There is nothing wrong with the code.
Your program compiles and starts without errors using the beta version of Visual C ++ 11, so the error seems to be fixed for the upcoming compiler publication.
Where is the capture bit? If you want to change a, you do not need [& a] at the beginning of your first lambda?
[&a]() { a = 1; },