为什么std :: scan_is在visual studio编译器中发出运行时错误?

时间:2017-05-08 19:29:25

标签: c++

示例here在Visual Studio 2013中发出内存访问冲突的运行时错误。

#include <locale>
#include <iostream>
#include <iterator>

int main()
{
    auto& f = std::use_facet<std::ctype<char>>(std::locale(""));

    // skip until the first letter
    char s1[] = "      \t\t\n  Test";
    const char* p1 = f.scan_is(std::ctype_base::alpha, std::begin(s1), std::end(s1));
    std::cout << "'" << p1 << "'\n";

    // skip until the first letter
    char s2[] = "123456789abcd";
    const char* p2 = f.scan_is(std::ctype_base::alpha, std::begin(s2), std::end(s2));
    std::cout << "'" << p2 << "'\n";
}

为什么?编译器的实现错误了吗?

1 个答案:

答案 0 :(得分:3)

auto& f = std::use_facet<std::ctype<char>>(std::locale(""));导致错误。引用f是null对象的别名。似乎这个实现适用于gcc C + 11及更高版本的编译器,但它在Microsoft编译器中不起作用。因此,Visual Studio 2013中的正确实现&amp;我测试的2015年是:

#include "stdafx.h"
#include <locale>
#include <iostream>
#include <iterator>

int main()
{
    std::locale loc(std::locale(""));
    //auto& f = std::use_facet<std::ctype<char>>(std::locale(""));
    auto& f = std::use_facet<std::ctype<char>>(loc);
    // skip until the first letter
    char s1[] = "      \t\t\n  Test";
    const char* p1 = f.scan_is(std::ctype_base::alpha, std::begin(s1), std::end(s1));
    std::cout << "'" << p1 << "'\n";

    // skip until the first letter
    char s2[] = "123456789abcd";
    const char* p2 = f.scan_is(std::ctype_base::alpha, std::begin(s2), std::end(s2));
    std::cout << "'" << p2 << "'\n";
}