Reputation: 61
I am little confused with the return type of const_cast
? Does the type inside the angular brackets <>
is the return type?
const int i = 5;
int b = const_cast<int&>(i);
Is const_cast
returning int&
(integer reference), if yes then why how we storing it in integer? Or we should modify the code to:
const int i = 5;
int & b = const_cast<int&>(i);
Upvotes: 0
Views: 65
Reputation: 227468
Does const_cast return the type specified inside angular bracket
It evaluates to an expression of the type in the angular brackets. What matters here is how you use that expression:
const int i = 5;
int b = const_cast<int&>(i);
In this case, b
is just a copy of i
. The cast is not required.
const int i = 5;
int & b = const_cast<int&>(i);
Here, b
refers to i
. Note that using it to modify the value of i
is undefined behaviour.
Upvotes: 3
Reputation: 172964
Does the type inside the angular brackets <> is the return type?
Yes, the return type of const_cast<int&>(i)
is int&
. After that you assign it to a int
, and the value get copied.
And in int & b = const_cast<int&>(i);
, you assign it to a int&
, now b
is the reference to i
. Pay attention to that any modification on b
will cause undifined behaviour.
Upvotes: 0
Reputation: 98436
Yes. But instead of returning you should say that the type of the resulting expression is the type in <>
.
When that type is a reference, as in const_cast<int&>
, it means that it is a l-value. In the first case there is no difference, as it is immediately converted to an r-value anyway. But then, the const
in such an r-value is ignored, so:
int b = const_cast<int&>(i); //ok
int b = const_cast<int>(i); //also ok
int b = i; //hey! also ok
In the second case there is a difference, because there is no l-value to r-value conversion:
int &b = const_cast<int&>(i); //ok
int &b = const_cast<int>(i); //error: cannot bind a reference to an r-value
int &b = i; //error: cannot bind a `int&` to a `const int&`
Upvotes: 3