C++中的wchar_t(转)

以下讨论都基于C++的定义

在C++的标准定义中
Type wchar_t is a distinct type whose values can represent distinct
codes for all members of the largest extended character set specified
among the supported locales
. Type wchar_t shall have the same
size, signedness, and alignment requirements as one of the other
integral types, called its underlying type.

...

A character literal that begins with the letter L, such as L'x', is a
wide-character literal. A wide-character literal has type wchar_t.
The value of a wide-character literal containing a single c-char has
value equal to the numerical value of the encoding of the c-char in
the execution wide-character set. The value of a wide-character lit-
eral containing multiple c-chars is implementation-defined.

    按照我的理解,这意味着:
    1. 编译器需要保证wchar_t与某种整数类型拥有相同的大小,符号,对齐要求.这个"某种整数类型"是由编译器定义的.这意味着 wchar_t(0x8000 > 1)的结果是取决于编译器的. 在VC里面,如果设置了编译选项"/Zc:wchar_t-",那么wchar_t会被默认定义为无符号的"unsigned short".另外"signed wchar_t"或"unsigned wchar_t"在C++是不存在的

    2.与C不同,wchar_t必须是一个内建(build-in)类型,我猜这是为了重载和模板特化的需要,看看iostream重载的类型大概就明白了.这里可以引申出另外一个话题: char 既不是 "signed char", 也不是"unsigned char"

    3.C++的标准文本没有将wchar_t 和 unicode关联起来,标准仅仅要求,wchar_t 能够用唯一的编码表示该编译器所有locale的字符全集中的任何一个字符即可,虽然从需求上来讲,wchar_t 也是一种unique-code,但是,一个特立独行的编译器,完全有权利定义一套完全不同于unicode的hexie-code,不过,这个hexie-code至少需要保证在数值上,能够兼容 char 类型的表数范围,通常意味着 hexie-code的 0-255必须是和char的0-255表示相同的字符

    4.众所周知的,windows的wchar_t是16位,linux的wchar_t是32位

    5.截至到VC8, VC的C运行库是不支持UTF-8的,也就是说setlocale(LC_CTYPE, "zh_CN.UTF-8")是无效的,setlocale(LC_CTYPE, "zh_CN.65001")也不行.单步跟踪后,发现在getqloc.c中,有以下代码

    // verify codepage validity
    if (!iCodePage || iCodePage == CP_UTF7 || iCodePage == CP_UTF8 ||
        !IsValidCodePage((WORD)iCodePage))
        return FALSE;

这段代码是VC8中新加的,VC7中没有,表现出来的不同是, VC8在setlocale的时候就失败了,而VC7直到真的使用mbstowcs这些函数的时候才会失败

http://hi.baidu.com/bbcallen/blog/item/e2e37b1b5add59d3ac6e7549.html

posted @ 2010-03-29 22:01  独奏者  阅读(4080)  评论(0编辑  收藏  举报