c32rtomb
和mbrtoc32
函数来自于<cuchar>
/<uchar.h>
,在C Unicode TR(draft)中被描述为在UTF-321和“多字节字符”之间进行转换。
(...) 如果
s
不是空指针,则c32rtomb
函数确定用于表示与给定的宽字符c32
相对应的多字节字符(包括任何转义序列)所需的字节数,并将多字节字符表示存储在由s
指向的数组的第一个元素中。 (...)
这里的“多字节字符表示”是什么意思?我实际上对以下程序的行为感兴趣:
#include <cassert>
#include <cuchar>
#include <string>
int main() {
std::u32string u32 = U"this is a wide string";
std::string narrow = "this is a wide string";
std::string converted(1000, '\0');
char* ptr = &converted[0];
std::mbstate_t state {};
for(auto u : u32) {
ptr += std::c32rtomb(ptr, u, &state);
}
converted.resize(ptr - &converted[0]);
assert(converted == narrow);
}
这个断言是否保证成立1?
1 在假设__STDC_UTF_32__
被定义的前提下工作。
setlocale
的调用,即使他的字符串完全在基本字符集内,断言也可能失败? - Nemosetlocale()
被调用时参数不是"C"
,那么是的。例如,在一个执行编码与 ASCII 兼容的系统上调用setlocale("en_US.EBCDIC")
(假设这是一个带有明显含义的支持区域设置)将导致c32rtomb()
产生 EBCDIC 字符串,而std::string narrow
仍然保持 ASCII 编码。 - bames53