casting const to pass it to function that takes reference, what happens?
-
27-10-2019 - |
Question
Can anyone tell me what happens here when passing to g in the main, is it static_cast?
int & g (int&x){x++ ; return x ; }
int main()
{
const int a=5 ;
cout<<g((int&)a)<<endl;
}
I am sure that no copy is made, since the code above is similar to the one below :
class A
{
public:
A()
{
cout << "calling DEFAULT constructor\n\n";
}
A(A& Other)
{
cout << "Calling COPY constructor\n\n";
}
~A()
{
cout << "Calling DESTRUCTOR\n\n";
}
};
A& g(A& x)
{
cout << "Inside g(A& x) \n\n";
return x;
}
void main()
{
const A a;
g(const_cast<A&>(a));
}*/
Thanks in advance :)
Solution
static_cast
cannot remove constness. This is a const_cast
.
At runtime, this code (the first example) yields undefined behavior because you modify a const object.
OTHER TIPS
A C-style cast is a vicious thing -- it will do everything that a reinterpret_cast<>
or a const_cast<>
will do. It's one of those "the power of a chainsaw with the ease-of-use of a chainsaw" things that C is rightly infamous for.
Using the C++-style casts will show that you need to do a const_cast<>
, and then you should ask yourself why and find a better way to do it.
For int, there's no code needed to just pass the reference in. Your cast lets it compile.