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


Question

I have:

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

The error: invalid static_cast from type ‘unsigned char*’ to type ‘const char*’

What's the correct way to cast here in C++ style?

1
75
3/18/2009 4:06:11 PM

Accepted Answer

reinterpret_cast

45
3/18/2009 4:01:44 PM

char * and const unsigned char * are considered unrelated types. So you want to use reinterpret_cast.

But if you were going from const unsigned char* to a non const type you'd need to use const_cast first. reinterpret_cast cannot cast away a const or volatile qualification.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon