Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How const_cast does it job?

Tags:

c++

c++11

I already know what const_cast does. However I would like to know how it does the job. What exactly does the compiler do when it sees a const_cast ?

like image 449
Gabriel de Grimouard Avatar asked Nov 29 '25 03:11

Gabriel de Grimouard


1 Answers

Recall that const_cast is safe only when the actual variable has been declared non-const. Since all const_cast<T>(...) does is removing const-ness from a type*, it basically does nothing beyond telling the compiler that you know what you are doing. Const-ness is a compile-time concept, so casting it away also happens inside the compiler.

* It can also add/remove const-ness or force it to be treated as if it were volatile, but all of that follows the same basic approach.

like image 131
Sergey Kalinichenko Avatar answered Dec 01 '25 18:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!