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

前端 未结 7 933
天涯浪人
天涯浪人 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:17

    Too many comments to make to different answers, so I'll leave another answer here.

    You can and should use reinterpret_cast<>, in your case

    str.append(reinterpret_cast<const char*>(foo()));
    

    because, while these two are different types, the 2014 standard, chapter 3.9.1 Fundamental types [basic.fundamental] says there is a relationship between them:

    Plain char, signed char and unsigned char are three distinct types, collectively called narrow character types. A char, a signed char, and an unsigned char occupy the same amount of storage and have the same alignment requirements (3.11); that is, they have the same object representation.

    (selection is mine)

    Here's an available link: https://en.cppreference.com/w/cpp/language/types#Character_types

    Using wchar_t for Unicode/multibyte strings is outdated: Should I use wchar_t when using UTF-8?

    0 讨论(0)
提交回复
热议问题