C++ style cast from unsigned char * to const char *

前端 未结 7 945
天涯浪人
天涯浪人 2020-12-07 15:44

I have:

unsigned char *foo();
std::string str;
str.append(static_cast(foo()));

The error: invalid static_cast from

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 16:10

    unsigned char* is basically a byte array and should be used to represent raw data rather than a string generally. A unicode string would be represented as wchar_t*

    According to the C++ standard a reinterpret_cast between unsigned char* and char* is safe as they are the same size and have the same construction and constraints. I try to avoid reintrepret_cast even more so than const_cast in general.

    If static cast fails with what you are doing you may want to reconsider your design because frankly if you are using C++ you may want to take advantage of what the "plus plus" part offers and use string classes and STL (aka std::basic_string might work better for you)

提交回复
热议问题