En MS Visual C++ 2010 SP1 este código se bloquea:std :: función se bloquea cuando se utiliza en conjunto en la pila
#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;
}
Cuando el segundo elemento de matriz se construye corrompe el primer elemento de matriz.
¿Esto es un error en el compilador o he hecho algo que no es compatible con el estándar C++ 11?
EDITAR
Este código funciona en 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;
}
No sé la respuesta pero FWIW, funciona en GCC 4.6 una vez que haya eliminado los detalles de MSVC. – Mat
Gracias por probar con GCC 4.6. Esto proporciona alguna evidencia de un error en el compilador de MS. – frast
Los punteros a las funciones lambda están en mal estado, de hecho, Minimicé el problema en ese código: # include # include int main (int argc, char * argv []) { \t std: : función s [] = { \t \t []() {std :: cout << "f0" << std :: endl;}, \t \t []() {int a = 1; std :: cout << "f1" << std :: endl;} \t}; \t s [0](); // salida f1 en lugar de f0 \t s [1](); // Este falló, el puntero a la función probablemente está en mal estado return 0; } Cuando llama a s [0], muestra "f1" Y s [1] realmente falla. –
Mesop