gpt4 book ai didi

c++ - 为什么 std::scan_is 在 vi​​sual studio 编译器中发出运行时错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:59:58 24 4
gpt4 key购买 nike

示例 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";
}

这是为什么呢?编译器的错误实现?

最佳答案

auto& f = std::use_facet<std::ctype<char>>(std::locale("")); 行导致错误。引用 f 是空对象的别名。似乎此实现适用于 gcc C+11 及更高版本的编译器,但不适用于 Microsoft 编译器。因此,我测试过的 Visual Studio 2013 和 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";
}

关于c++ - 为什么 std::scan_is 在 vi​​sual studio 编译器中发出运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43855859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com