Reputation: 24705
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.
Upvotes: 1
Views: 1259
Reputation: 170074
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.
Upvotes: 2