GodBolt
考虑以下代码片段:
using A = void(*)(int);
A foo(const void* ptr)
{
return reinterpret_cast<A>(ptr);
}
GCC 10 喜欢这个就好了。但是,clang++-10 说这是一个错误!<source>:5:12: error: reinterpret_cast from 'const void *' to 'A' (aka 'void
(*)(int)') casts away qualifiers
return reinterpret_cast<A>(ptr);
^~~~~~~~~~~~~~~~~~~~~~~~
函数在 C++(和 C)中是不可变的,并且没有“const 函数”。那么为什么 clang++ 在这里提示呢?
最佳答案
因为标准是这么说的。
[expr.reinterpret.cast]/2:
The
reinterpret_cast
operator shall not cast away constness.
[expr.const.cast]/7:
A conversion from a type
T1
to a typeT2
casts away constness ifT1
andT2
are different, there is a cv-decomposition ofT1
yielding n such thatT2
has a cv-decomposition of the formand there is no qualification conversion that converts
T1
to
这里 T1 是
const void*
, T2 是 void (*)(int)
, n = 1, T2
的 cv 分解有 cv0 = "", P0 = "pointer to", cv1 = "", U2 = void(int)
,所以对应版本T1
是 void*
.没有来自 const void*
的资格转换至 void*
.因此,转换抛弃了常量性并且不能由 reinterpret_cast
执行。 .
关于c++ - clang 认为我需要指向 "const function"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62961212/