3

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;
}
Green goblin
  • 9,898
  • 13
  • 71
  • 100
  • 3
    Probably neither, but if you run into a situation where you're absolutely forced to, `const_cast` is more explicit as to what you're doing. – chris Jul 27 '12 at 00:06

5 Answers5

8

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;
}
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
2

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.

Puppy
  • 144,682
  • 38
  • 256
  • 465
1

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.

David Titarenco
  • 32,662
  • 13
  • 66
  • 111
1

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.

pmr
  • 58,701
  • 10
  • 113
  • 156
1

It's safer, but in a different way than you imagine.

It's safer because you explicitly state you're casting away constness.

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625