简体   繁体   中英

what does the presence of & mean in const_cast template parameter

I was going over the following example

const int a = 12;
int b;
b = const_cast<int&>(a);  

and I wanted to know what & in the template parameter type signifies above and why it wont work without the & ?

Update:

Let me rephrase my question . I understand its a reference but what variable is it referring to ? For instance here it states that incase of pointers it references the original (uncast) pointer. I want to know what it references incase of non pointer types and how can b ba reference when it wasnt declared as a reference ?

const_cast is not a template, but rather a type cast. What appears to be a template argument is the destination type for the cast, and in this case it means that you want to obtain a non-const reference to int that refers to the same objects as a .

a is const int& when you do the const_cast as you wrote it.

You can only modify cv-qualifiers of pointer and reference types with const_cast , not of values. This is because specifying constness for rvalues only makes sense if this is of reference or pointer type and can thus be modified.

So if you just want the (non-const) value of the variable a , simply write

b = a;

as the const-ness is ignored anyway. b is then copy-constructed from a .

Basically a is const, b is not const

so const_cast basically says b is stored at a but removes the const.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM