1

I see this post which explain the const_cast<> and says it is beneficial when pointers/references are used. However, consider the following codes:

1-

const_cast<SCOTCH_Num*>(xadj)

which I get invalid const_cast from type 'cost label* {aka const long int *}' to type 'SCOTCH_Num* {aka int*}'. So, pointers are casted. Isn't that?

and

2-

(SCOTCH_Num*)(xadj)

which I get warning: use of old-style cast [-Wold-style-cast]

You may ask about the variable definitions, but the aka part in the error is clear. If I have propose more details, please let me know.

mahmood
  • 23,197
  • 49
  • 147
  • 242

1 Answers1

2

const_cast is only to be used for modifying const or volatile qualifiers on pointers to the same type. You cannot use it to cast between unrelated pointer types. A long int * is a pointer to an object type different than int*, so a const_cast will be ill-formed. And that's good, because you shouldn't be caught unaware when doing something risky like that.

The c-style cast will do the conversion at virtually any cost. It's a blunt tool that pays little regard to the type system. The whole reason C++ introduced different types of casts for different scenarios is to avoid this "casting at all costs" behavior. It's to give the programmer control and precision while casting.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • You might want to add _"Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior."_ – Richard Critten Feb 05 '18 at 14:08
  • @RichardCritten - I don't really, since it's not the subject of the question. I'd rather stay on point, which is the casts themselves. There's possible UB if we use the result of the C-style cast too, due to strict aliasing. Delving into that is a tangent as well. – StoryTeller - Unslander Monica Feb 05 '18 at 14:15