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

106 Views Asked by At
#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?

1

There are 1 best solutions below

0
On BEST ANSWER

I tried building your code with VS2015, and it runs fine in debug build. I got this output:

Start...
Ctor
Complete...

without any "crash".

It may be a compiler bug with VS2013. You may want to upgrade to a new C++ compiler.