简体   繁体   中英

C++: Is it safe to cast from wchar_t* to unsigned short*?

C++: Is it safe to cast from wchar_t* to unsigned short* ?

Because I am using the SAXReader of MSXML2 I need to pass unsigned short* some of its methods. The values I need to pass are wchar_t, so it is safe to do this cast?

In general the cast is not safe since strict aliasing rules forbid it.

But you would get away with it if wchar_t is a typedef for unsigned short . If it is you could enforce that at compile time using a static_assert , based on the value of

std::is_same<whar_t, unsigned short>::value

Note further though that such an implementation is relying on your compiler not implementing the standard correctly: Formally wchar_t has the same size, signedness, and alignment as one of the integer types, but is a distinct type." Therefore a typedef would not be compliant and the value assertion should always fail.

Reference: http://en.cppreference.com/w/cpp/language/types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM