In MS Visual C++ 2010 SP1 questo codice crash:std :: funzione si blocca quando usato in matrice sulla 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;
}
Quando il secondo elemento dell'array è costruito corrompe primo elemento dell'array.
È un errore nel compilatore o ho fatto qualcosa che non è supportato nello standard C++ 11?
EDIT
Questo codice funziona 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;
}
Non conosco la risposta, ma FWIW, funziona su GCC 4.6 dopo aver rimosso le specifiche MSVC. – Mat
Grazie per il test con GCC 4.6. Ciò fornisce alcune prove per un bug nel compilatore MS. – frast
I puntatori alle funzioni lambda sono in disordine, infatti, ho ridotto al minimo il problema in quel codice: #include #include int main (int argc, char * argv []) { \t std: : funzione s [] = { \t \t []() {std :: cout << "F0" << std :: endl;}, \t \t []() {int a = 1; std :: cout << "f1" << std :: endl;} \t}; \t s [0](); // output f1 invece di f0 \t s [1](); // Questo errore, il puntatore alla funzione è probabilmente incasinato return 0; } Quando si chiama s [0], esce "f1" E s [1] in realtà fallisce. –
Mesop