gpt4 book ai didi

c++ - 当使用 _ENABLE_PER_THREAD_LOCALE 时,STL 对象使用 C 运行时库语言环境进行浮点转换?

转载 作者:行者123 更新时间:2023-11-30 02:10:55 25 4
gpt4 key购买 nike

C 运行时语言环境由 setlocale 设置。标准 C++ 库 (STL) 语言环境由 std::locale 类设置,并且可以在单个 STL 对象(如 std::istringstream 等)上设置。

函数 _configthreadlocale(_ENABLE_PER_THREAD_LOCALE) 允许在每个线程的基础上设置 C 运行时语言环境。

不幸的是,启用了 _configthreadlocale(_ENABLE_PER_THREAD_LOCALE) 的线程中的 STL 对象似乎正在使用 C 运行时语言环境。或者至少使用 C 运行时语言环境的小数点。

在没有 _ENABLE_PER_THREAD_LOCALE 的线程中没有问题。

Paavo 在 2008 年提出了类似的问题,但没有答案:_configthreadlocale and localeconv

以下代码显示了问题:

//Enable per thread locale in current thread  
_configthreadlocale(_ENABLE_PER_THREAD_LOCALE)

//Create istringstream object
std::istringstream LibraryStream;
//Create double object
double Value = 0;
//Create std::locale object with "C" locale ("." as decimal point)
std::locale StreamLoc("C");
//Set C Runtime locale to danish ("," as decimal point)
setlocale(LC_ALL, "danish");

//Set the "C" locale on the istringstream object
LibraryStream.imbue(StreamLoc);
//Get the locale of the istringstream object for test (returns "C" as expected)
std::locale NewStreamLoc = LibraryStream.getloc();

//Set floating point string with "C" locale decimal point in istringstream object
LibraryStream.str("60.258351");
//Convert the string to double
LibraryStream >> Value;

//Now the expected value of "Value" is 60.258351, but it is 60.000
//when debugging the conversion, I can see that "," is used as decimal point

有没有人遇到过这种情况?难道我做错了什么?有解决方案的建议吗?

提前致谢/TEB

最佳答案

由于 C++ 标准库最近才获得有关线程的知识,所以这种明显的二分法并不让我感到惊讶。对不同场景中发生的情况进行了详尽的讨论(特定于 Microsoft,但作为一般背景似乎很有帮助)here .

总结:

To change the locale using the C++ Runtime Library, use the locale Class. By calling the locale::global method, you change the locale in every thread that has not explicitly enabled per-thread locale. To change the locale in a single thread or portion of an application, simply create an instance of a locale object in that thread or portion of code.

关于c++ - 当使用 _ENABLE_PER_THREAD_LOCALE 时,STL 对象使用 C 运行时库语言环境进行浮点转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4145696/

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