Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does const_cast ever cause actual code emission?

Is it true that const_cast is just a way to tell the compiler "stop moaning, treat this as a non-const pointer"? Are there any cases when const_cast itself is translated into actual machine code?

like image 990
sharptooth Avatar asked Apr 17 '09 07:04

sharptooth


People also ask

What is true for 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.

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.

Why does const cast exist?

The whole purpose of const is to prevent you from modifying something, that's why your code generates an error. Adding in const_cast is basically telling the compiler to shut up, that you know what you're doing.

How do I remove a const?

The statement int* c = const_cast<int>(b) returns a pointer c that refers to a without the const qualification of a . This process of using const_cast to remove the const qualification of an object is called casting away constness.


1 Answers

No, it just removes const attribute at compile time.

like image 117
Evgeny Lazin Avatar answered Oct 04 '22 12:10

Evgeny Lazin