在MS Visual C ++ 2010 SP1中,此代码崩溃:
#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;
}
当构造第二个数组元素时,它会破坏第一个数组元素。
这是编译器中的错误还是我做过C ++ 11标准不支持的事情?
修改
此代码适用于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;
}
答案 0 :(得分:2)
这是编译器错误。您的代码没有任何问题。
您的程序使用Visual C ++ 11 Beta编译并运行时没有错误,因此该错误似乎已为即将发布的编译器修复。
答案 1 :(得分:0)
捕获位在哪里?如果你想修改一个,你不需要在第一个lambda的开头有[&amp; a]吗?
[&a]() { a = 1; },