Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage(s) of const_cast<>

Tags:

c++

const-cast

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.

like image 409
ereOn Avatar asked Apr 20 '10 08:04

ereOn


People also ask

What is the use of const_cast?

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.

Why is const_cast allowed?

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.

Is const_cast undefined behavior?

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.

Is const_cast safe?

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.


2 Answers

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 image 51
jk. Avatar answered Oct 06 '22 10:10

jk.


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());     } }; 
like image 34
GManNickG Avatar answered Oct 06 '22 10:10

GManNickG