4 ms·
A reinterpret_cast is something that shows up very rarely, so it’s fine that it’s not concise. And when it is used, it usually can do with a function naming it.
by BenFrantzDale 4y ago
A reinterpret_cast is something that shows up very rarely, so it’s fine that it’s not concise. And when it is used, it usually can do with a function naming it. I try to have a “no raw reinterpret_cast” view unless it’s chars to unsigned chars for string stuff. And as others have said, it’s grepable and can’t cast away constness. If I’m handing a const unsigned char* to a function taking a char* that I know wind modify the data, I don’t want that to be (char*)ptr. I want it to be const_cast<char*>(reinterpret_cast<const char*>(ptr)) because yikes, it should stand out because it’s awful.
And then I’d wrap that godawful cast in a function overloading the legacy C interface, so the overload has one job: to encapsulate the logic that the legacy function isn’t const correct. So then I’d have like void wrappedFoo(std::string_view s) { foo(const_cast<char*>(reinterpret_cast<const char*>(s.data())), s.size()); } with lots of comments about the cast.