Gabrielle de Grimouard
Gabrielle de Grimouard

Reputation: 2005

How const_cast does it job?

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 ?

Upvotes: 2

Views: 112

Answers (3)

Peter
Peter

Reputation: 36597

The depends on the compiler, of course.

But, over-simplistically in general terms, the compiler translates the code within each scope (function block, nested blocks, etc) into some internal representation of the variables/objects, and sequence of operations on them. The objects may be named (e.g. corresponding to variables declared in your code) or unnamed (e.g. temporaries). Using that representation, it will keep track of the cv-qualification of each object (whether it is marked const, volatile, or a combination of those) and will test validity of operations on the objects (e.g. to reject assignment to a const int after initialisation).

When it encounters a const_cast, the compiler will register an entry with different const qualification, and do its subsequent checks accordingly, until the end of the containing scope.

All of this happens during compilation. There will often be no evidence of it in emitted object code, particularly if the compiler recognises that two pointers reference the same object, just with different cv-qualification.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

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.

Upvotes: 6

Brian Bi
Brian Bi

Reputation: 119194

A const_cast doesn't compile to any instructions; it just returns the same value with the cv-qualifier(s) removed. It's a way to break the type system that normally prevents the modification of a const object (or a non-const object through a const glvalue).

Upvotes: 4

Related Questions