Static_cast wchar_t * to int * or short * - why is it illegal?

In Microsoft VC2005 and g ++ compilers, the following errors result in an error:

In win32 VC2005: sizeof (wchar_t) is 2

wchar_t *foo = 0;
static_cast<unsigned short *>(foo);

Results in

error C2440: 'static_cast' : cannot convert from 'wchar_t *' to 'unsigned short *' ...

On Mac OS X or Linux g ++: sizeof (wchar_t) - 4

wchar_t *foo = 0;
static_cast<unsigned int *>(foo);

Results in

error: invalid static_cast from type 'wchar_t*' to type 'unsigned int*'

Of course, I can always use reinterpret_cast. However, I would like to understand why the compiler is considered illegal for static_cast for the corresponding integer type. I am sure there is a good reason ...

+3
source share
4 answers

. . , , . , . , , , . Reinterpret_cast - , hacve, , , os .

+6

char, wchar_t . , 2, wchar_t c,

*reinterpret_cast<unsigned short *>(&c)

:

static_cast<unsigned short>(c)

, , wchar_t - + , c unsigned 2 ^ N, . - - ( ).

, , static_cast . , unsigned short*, " , , ", ?

, , , , - , static_cast .

, , " " wchar_t, , . , , _cast , -, , . , reinterpret_cast , . , , , , , reinterpret_cast ed .

+4

static_cast , : std:: ostream & std:: ofstream &. wchar_t , . ( ) reinterpret_cast

, MSV++ - wchar_t (), .

+2

" , ".

, , . ++, .

", wchar_t, , int. ".

. , , wchar_t, . , , .

, reinterpret_cast, , , . , .

. A wchar_t int short.

+1
source

Source: https://habr.com/ru/post/1714503/


All Articles