Using const_cast to add const-ness - bad idea?

c++, const-cast, pointers

Solution

You should not use `const_cast` to add `const`, because:

it's unnecessary. `T*` converts implicitly to `const T*`. Your question states that `char sourcebuffer[] = {0x00}; copyfunction(sourcebuffer);` is an error, but that's not true.

it's potentially (albeit unlikely) harmful. It can remove `volatile` from the pointer type, which is not the intention here and would result in undefined behavior if `sourcebuffer` were declared as `volatile sourcebuffer[]`.

Problem

as we all know the usage of const_cast to remove the const-ness of a pointer should be avoided. But how is it about the other way around? For my use case I have a function that copies data (bytes) from a non-const source buffer. I thought a good design decision would be to declare the parameter according to that source buffer fully const. ``` void copyfunction(const char* const data) { ... } ``` For a function call like below this would lead to a pointer-type error 'const char* const <-> char*'. ``` void main() { char sourcebuffer[] = {0x00}; copyfunction(sourcebuffer); } ``` Sure, now I could simply declare the `sourcebuffer` as const but in my case I don't have access to that variable because it's from a different code location (external library). ``` void main() { char sourcebuffer[] = {0x00}; copyfunction(const_cast<const char* const>(sourcebuffer)); } ``` However the code beyond would work but is it good style (according to my use case)? I thought declaring the parameter of the `copyfunction` as const assures the user of not modifying (read-only) the pointer or the location of the source buffer itself. So in this case the const_cast would only be a necessary evil to enable to function call and not willfully remove the const-ness of a pointer... Greets

Original source