Search code examples
c++castingsaxparser

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?


Solution

  • 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