const_cast vs reinterpret_cast

Abh*_*jit 7 c++ casting const reinterpret-cast

参考SO C++ FAQ 什么时候应该使用static_cast,dynamic_cast和reinterpret_cast?.

const_cast用于删除或添加const到变量,它是唯一可靠,定义和合法的方法来删除constness.reinterpret_cast用于更改类型的解释.

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

我知道使用reinterpret_cast甚至添加constness是不是很理智,但是使用reinterpret_cast来增加常量会是UB还是潜在的定时炸弹?

我在这里感到困惑的原因是因为声明

很大程度上,reinterpret_cast的唯一保证是,如果将结果转换回原始类型,您将得到完全相同的值.

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

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

5.2.10重新解释强制转换(7)......当"指向T1的指针"类型的prvalue v转换为"指向cv T2的指针"类型时,如果两个T1都为static_cast(static_cast(v))和T2是标准布局类型(3.9),T2的对齐要求不比T1更严格........

Sta*_*ked 11

reinterpret_cast更改对象内数据的解释.const_cast添加或删除const限定符.数据表示和常量是正交的.所以有不同的演员关键词是有意义的.

因此,如果我使用reinterpret_cast添加constness,并且如果你将结果重新解释为原始类型,它应该返回原始类型而不应该是UB,但这违反了一个事实,即只应该使用const_cast来删除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
Run Code Online (Sandbox Code Playgroud)

  • 非const对象总是可以隐式转换为const,而不需要任何强制转换.我不明白为什么`reinterpret_cast`应该是这个规则的例外. (2认同)

Mik*_*one 5

你不应该只是添加constwith reinterpret_cast。Areinterpret_cast应该主要是:重新解释指针(或其他)。

换句话说,如果你要从const char*char*(希望因为有一个糟糕的 API 你不能改变),那么const_cast就是你的朋友。这就是它的全部目的。

但是,如果您需要从MyPODType*const char*,则需要reinterpret_cast,并且不需要在其上添加 就很好了const_cast