Referring to the SO C ++ FAQ When should static_cast, dynamic_cast and reinterpret_cast be used? .
const_cast is used to remove or add a constant to a variable and its only reliable, defined and legal way to remove a constant. reinterpret_cast is used to change the interpretation of a type.
I understand in a reasonable way why a constant variable should be cast non-const only with const_cast, but I cannot find a reasonable justification for the problems using reinterpret_cast instead of const_cast to add a constant.
I understand that using reinterpret_cast to even add a constant is not normal, but will it be a UB or a potential time bomb to use reinterpret_cast to add a constant?
The reason I was confused is due to the expression
In many ways, the only guarantee you get with reinterpret_cast is that if you return the result back to the original type, you will get the exact same value.
So, if I add a constant using reinterpret_cast, and if you reinterpret the result returning to the original type, it should return to the original type and should not be UB, but this violates the fact that you need to use const_cast to remove the constant
In a separate note, the standard ensures that you can add Constness using the reinterpret case
5.2.10 Re-interpret casting (7) ... When a v value of type "pointer to T1" is converted to type "pointer to cv T2", the result is static_cast (static_cast (v)) if both T1 and T2 are equal to standard formats (3.9) and the alignment requirements of T2 are no more stringent than that of T1 ........
source share