In MS Visual C++ 2010 SP1 this code crashes:
#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 the second array element is constructed it corrupts the first array element.
Is this an error in the compiler or have I done 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 bug. There's nothing wrong with your code.
Your program compiles and runs without error using the Visual C++ 11 Beta, so the bug appears to have been fixed for the forthcoming release of the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With