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
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[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With