使用空字符串 "" 创建 std::locale

Creating an std::locale with an empty string ""

问题

是否使用空字符串构建 std::locale 以使用户首选的本地语言环境成为标准的一部分?如果是,你能指出一个明确说明的来源吗?

问题描述

std::locale 文档中的示例有这一行:

std::wcout << "User-preferred locale setting is " << std::locale("").name().c_str()

这暗示使用空字符串创建语言环境将 return 成为用户首选的本机语言环境。快速谷歌搜索后,这个 article 还提到:

The empty string tells setlocale to use the locale specified by the user in the environment.

然而,当查看 documentation for std::locale 构造函数时,没有提及提供空字符串的特殊情况。

引述如下:

3-4) Constructs a copy of the system locale with specified std_name (such as "C", or "POSIX", or "en_US.UTF-8", or "English_US.1251"), if such locale is supported by the operating system. The locale constructed in this manner has a name.

draft standard[locale.cons]中说:

explicit locale(const char* std_name);
  1. Effects: Constructs a locale using standard C locale names, e.g., "POSIX". The resulting locale implements semantics defined to be associated with that name.

  2. Throws: runtime_error if the argument is not valid, or is null.

  3. Remarks: The set of valid string argument values is "C" , "" , and any implementation-defined values.

这表明 "" 是一个有效的构造函数参数,参数是标准的 C 语言环境名称。

然后在[c.locale]中明确引用标准C头文件<locale.h>.

引用自 C 标准 (C99),7.11.1.1/3:

A value of "C" for locale specifies the minimal environment for C translation; a value of "" for locale specifies the locale-specific native environment. Other implementation-defined strings may be passed as the second argument to setlocale.

我认为这意味着您的问题的答案是 "yes":名称 "" 指的是本地语言环境。