Killian G.
Killian G.

Reputation: 380

How does const_cast works?

I want to know how does const_cast work. I know how to use it but how in real fact does it works ? Does it return a non-const copy of the reference/pointer ?

Upvotes: 3

Views: 785

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

const is part of the type system.

Just like when you write int x; you are telling your compiler that you want an integer called x, when you write const int x; you are telling your compiler that you want an immutable integer called x.

Then when you write int& ref = const_cast<int&>(x); you tell the compiler that you now want a mutable reference to that integer (and that you take responsibility for any consequences of such hackery).

There is no effect at runtime. It's all just communication between you and the compiler. How it implements types is extremely complicated but if you are one of the five or six people in the world who understands the GCC/LLVM/Visual Studio source code then you could study it to find the specific details that make const_cast work inside the compiler. I'm not sure what useful information that would tell you though, unless you're planning to develop new features for said compiler.

You can, however, read the "rules" of what it's supposed to do, in the standard.

In brief, though, to answer your question: like any cast, it evaluates to a copy if you ask for a copy.

const int x = 42;

auto y1 = const_cast<int>(x);   // pointless tbh because you could copy anyway!
auto y2 = const_cast<int*>(&x); // pointer cast
auto y3 = const_cast<int&>(x);  // reference cast

Upvotes: 4

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122457

Not the way it works exactly, but you can think of constcorrectness being checked in an early stage of compilation and after that const doesnt matter anymore. Ie all that happens is that you tell the compiler to treat the object as non-const.

Consider this example:

int main() {
    int x = 5;
    const int& y = x;
    const_cast<int&>(y) = 7;   // ok, because x is actually not const
}

Once the compiler made sure that the code is const correct, it is equivalent to

int main() {
    int x = 5;
    int& y = x;
    y = 7;
}

Just don't forget that you are not allowed to cast const away on something that actually is const. In the example if x was const then you could still cast away constness on y, get no compiler error, but undefined behaviour at runtime.

Upvotes: 4

Related Questions