从"const T pointer" "void pointer" const_cast失败

const_cast to "void pointer" from "const T pointer" fails

本文关键字:const pointer cast 失败 void      更新时间:2023-10-16

为什么下面的代码无法编译?

CFDictionaryRef dictionary;

CFDictionaryApplyFunction(dict, set, const_cast(dictionary));

 error: const_cast from 'CFDictionaryRef' (aka 'const __CFDictionary *') to 'void *' is not allowed
    CFDictionaryApplyFunction(scoped, setDictionary, const_cast<void *>(dictionary));
                                                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

如果我将c风格的类型强制转换设置为void *,它可以正常工作

Do reinterpret_cast<void *>(const_cast< __CFDictionary * >(dictionary))

const_cast仅用于在const指针或引用与它们的非const对等物之间进行强制转换。要转换为不同的类型(在您的例子中是void*),您需要使用reinterpret_castreinterpret_cast基本上是将相同的比特序列"重新解释"为不同的类型。但是,不允许抛弃constness,因此需要同时使用两种强制转换。

编辑:正如@AnT指出的那样,由于目标是void *,您可以使用static_cast而不是reinterpret_cast。事实上,它被认为是更安全的,因为标准保证您得到相同的地址作为结果。另一方面,reinterpret_cast只保证通过reinterpret_cast对第一次强制转换的结果获得原始值。然而,这只适用于一组有限的转换(void *,基派生类对)。reinterpret_cast更通用,尽管您依靠编译器来做合理的事情。