Why does std :: scan_is emit a runtime error in the visual studio compiler?

The example here emits a run-time error with a memory access violation in 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";
}

Why? Incorrect implementation from the compiler?

+4
source share
1 answer

The line auto& f = std::use_facet<std::ctype<char>>(std::locale(""));causes an error. The f reference is an alias for the null object. This implementation seems to work for gcc C + 11 compilers and above, but it does not work on Microsoft compilers. So the correct implementation in Visual Studio 2013 and 2015 that I tested is as follows:

#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";
}
+3
source

Source: https://habr.com/ru/post/1676679/


All Articles