【问题标题】:Exception in debug mode when const member variable initialised in class declaration在类声明中初始化 const 成员变量时调试模式下的异常
【发布时间】:2017-08-29 08:34:28
【问题描述】:
#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;
}

以上代码在使用 Xcode 7.2.1 和 Clang 7.0.2 的 OS X 上以调试和发布模式成功构建和运行。

它还在 Windows 7 上使用 Visual Studio Express 2013 for Windows Desktop 在发布模式下成功构建和运行。

但是,在 Windows 上以调试模式运行时,它会崩溃。在构造函数完成执行之前发生访问冲突。控制台输出如下:

Start...
Ctor

如果m_validators 的初始化被移动到构造函数初始化列表,那么错误就会消失。

这可能是编译器错误还是声明有问题?

【问题讨论】:

  • VS2013 中的 C++11 功能集和实现不完整,因此很可能是编译器错误。尝试升级到 VS2015(或者为什么不升级到 VS2017?),看看效果会更好。

标签: c++ c++11 lambda stdmap std-function


【解决方案1】:

我尝试使用 VS2015 构建您的代码,它在调试构建中运行良好。我得到了这个输出:

Start...
Ctor
Complete...

没有任何“崩溃”。

这可能是 VS2013 的编译器错误。您可能需要升级到新的 C++ 编译器。

【讨论】:

    猜你喜欢
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2013-01-07
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多