c++ - const_cast 与 reinterpret_cast

标签 c++ casting constants reinterpret-cast

引用 SO C++ 常见问题 When should static_cast, dynamic_cast and reinterpret_cast be used? .

const_cast 用于删除或向变量添加常量,这是删除常量的唯一可靠、定义和合法的方法。 reinterpret_cast 用于改变类型的解释。

我以一种合理的方式理解,为什么一个 const 变量应该只使用 const_cast 转换为非 const,但我无法找出使用 reinterpret_cast 而不是 const_cast 来添加常量的问题的合理理由。

我知道使用 reinterpret_cast 来添加常量是不明智的,但是使用 reinterpret_cast 来添加常量会是 UB 还是潜在的定时炸弹?

我之所以在这里感到困惑是因为声明

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.

因此,如果我使用 reinterpret_cast 添加 constness,并且如果你将结果 reinterpret_cast 返回到原始类型,它应该返回到原始类型并且不应该是 UB,但这违反了一个事实,即应该只使用 const_cast 来删除常量

在单独的注释中,标准保证您可以使用重新解释案例添加常量

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........

最佳答案

reinterpret_cast 更改对象内数据的解释。 const_cast 添加或删除 const 限定符。数据表示和常量是正交的。因此,使用不同的 cast 关键字是有意义的。

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

那甚至无法编译:

int * n = new int;
const * const_added = reinterpret_cast<const int *>(n);
int * original_type = reinterpret_cast<int*>(const_added);
    // error: reinterpret_cast from type ‘const int*’ to type ‘int*’ casts away qualifiers

关于c++ - const_cast 与 reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14272578/

相关文章:

c++ - 使用 C++ REST SDK (Casablanca) 的 Http_client post 请求

javascript - 在 Google Sheets 脚本中声明 const 的替代方法

javascript - 在这种情况下范围如何工作?

c++ - 循环文件包含 C++

c++ - 尺寸、长度换算?

c++ - 为什么这个宏会产生 2?

c++ - 在哪里初始化 SSE 常量

C:在不强制转换的情况下对无符号变量执行有符号比较

ios - Swift - 任意数组到字符串数组

java - 将原始 int 转换为 Number