Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::function crashes when used in array on stack

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;
}
like image 745
frast Avatar asked Mar 30 '12 16:03

frast


1 Answers

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.

like image 196
James McNellis Avatar answered Sep 26 '22 09:09

James McNellis