mardi 29 août 2017

Exception in debug mode when const member variable initialised in class declaration

#include <functional>
#include <map>
#include <string>
#include <iostream>

class X
{
public:
    X()
    {
        std::cout << "Ctor\n";
    }

private:
    typedef std::map<std::string, std::function<void()>> ValidatorType;

    const ValidatorType m_validators = ValidatorType
    {
        {
            "some-string",
            []()
            {
                // validation code
                std::cout << "Validating...\n";
            }
        }
    };
};

int main()
{
    std::cout << "Start...\n";

    X x;

    std::cout << "Complete...\n";

    return 0;
}

The above code builds and runs successfully in debug and release mode on OS X using Xcode 7.2.1 and Clang 7.0.2.

It also builds and runs successfully in release mode on Windows 7 using Visual Studio Express 2013 for Windows Desktop.

However, it crashes when run in debug mode on Windows. An access violation occurs before the constructor finishes executing. The console output is as follows:

Start...
Ctor

If the initialisation of m_validators is moved to the constructor initialiser list then the error goes away.

Could this be a compiler bug or is there something wrong with the declaration?

Aucun commentaire:

Enregistrer un commentaire