Which is safer to use?
int main()
{
const int i=5;
int *ptr;
ptr=(int*)&i; <------------------- first
ptr=const_cast<int*>(&i); <-------------------Second
return 0;
}
Which is safer to use?
int main()
{
const int i=5;
int *ptr;
ptr=(int*)&i; <------------------- first
ptr=const_cast<int*>(&i); <-------------------Second
return 0;
}
It's safer in the sense that you won't get a cast that's something other than just removing const
:
int main()
{
const char i=5;
int *ptr;
ptr=(int*)&i; // the compiler won't complain
ptr=const_cast<int*>(&i); // will fail, since `i` isn't an int
return 0;
}
which doesn't necessary mean that the const_cast<>
is safe:
const int i=5;
int main()
{
int const& cri(i);
int& ri = const_cast<int&>(cri); // unsafe
ri = 0; // will likely crash;
return 0;
}
They are entirely equivalent, except that C-style casts present more of a maintenance headache over the const_cast
. If the code were frozen in time, they would be identical. The Standard says that the C-style cast may devolve to static
, reinterpret
, or const
cast or a combination of the three, or a strange funky cast that can access private bases for some reason. The point is, in this use case it is exactly equivalent to const_cast
.
I'm not sure about safety - I'm sure someone is more well-versed in this than I am - but C++-style casts are part of the language standard and should always be preferred over C-style casts (as a matter of both style as well as readability).
To amend my answer, it appears that C++-style casts are checked by the compiler whereas C-style casts fail at runtime; in that regard, C++-style casts are definitely safer.
Neither is safer than the other. In both cases undefined behavior will occur should you modify the value through one of the pointers that have been casted. const_cast
has the benefit of doing only what you want and expresses it clearly, while the C style cast could be everything and is not sensitive to the actual type of its argument.
It's safer, but in a different way than you imagine.
It's safer because you explicitly state you're casting away const
ness.
When someone sees your code, they think - "ok, here's a const_cast
, this argument must have been const. Let's take a closer look at this", whereas a regular cast just gets lost in the back of the mind when reading big chunks of code.