As a common rule, it is very often considered a bad practice to use const_cast<>()
in C++ code as it reveals (most of the time) a flaw in the design.
While I totally agree with this, I however wonder what are the cases were using const_cast<>()
is ok and the only solution.
Could you guys please give me some examples you know/you encountered ?
Thank you very much.
const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.
When it comes to removing constness, the purpose of const_cast is to allow you remove constness from an access path (pointer or reference) that leads to a non-constant object.
Even though const_cast may remove constness or volatility from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const or to access an object that was declared volatile invokes undefined behavior. So yes, modifying constant variables is undefined behavior.
const_cast is safe only if you're casting a variable that was originally non- const . For example, if you have a function that takes a parameter of a const char * , and you pass in a modifiable char * , it's safe to const_cast that parameter back to a char * and modify it.
it is pretty much designed to be only used with legacy APIs that are not const correct i.e. with a function you can't change that has non const interface but doesn't actually mutate anything on the interface
Like others have said, its primary purpose is to remove const
from objects in order to pass to non-const correct functions you know won't modify the argument.
There is a trick (by Meyers?) to avoid code duplication, and it goes like this:
struct foo { const return_type& get(void) const { // fancy pants code that you definitely // don't want to repeat return theValue; // and got it } return_type& get(void) { // well-defined: Add const to *this, // call the const version, then // const-cast to remove const (because // *this is non-const, this is ok) return const_cast<return_type&>(static_cast<const foo&>(*this).get()); } };
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