Note that there are some explanatory texts on larger screens.

plurals
  1. POconst_cast vs reinterpret_cast
    text
    copied!<p>Referring the SO C++ FAQ <a href="https://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-and-reinterpret-cast-be-used">When should static_cast, dynamic_cast and reinterpret_cast be used?</a>.</p> <p>const_cast is used to remove or add const to a variable and its the only reliable, defined and legal way to remove the constness. reinterpret_cast is used to change the interpretation of a type.</p> <p>I understand in a reasonable way, why a const variable should be casted to non-const only using const_cast, but I cannot figure out a reasonable justification of issues using reinterpret_cast instead of const_cast to add constness.</p> <p>I understand that using reinterpret_cast for even adding constness is not sane but would it be an UB or potential time bomb for using reinterpret_cast to add constness?</p> <p>The reason I was confused here is because of the statement</p> <blockquote> <p>Largely, the only guarantee you get with reinterpret_cast is that if you cast the result back to the original type, you will get the exact same value.</p> </blockquote> <p>So if I add constness using reinterpret_cast and if you reinterpret_cast the result back to the original type, it should result back to the original type and should not be UB, but that violates the fact that one should only use const_cast to remove the constness</p> <p>On a separate Note, the standard guarantees that You can add Constness using reinterpret case</p> <blockquote> <p>5.2.10 Reinterpret cast (7) ......When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is static_cast(static_cast(v)) if both T1 and T2 are standard-layout types (3.9) and the alignment requirements of T2 are no stricter than those of T1........</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload