简体   繁体   中英

const_cast for references and pointers

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM