You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中const char**转const void**是否合法?无C风格转换方法

在C++中合法转换const char到const void的方法

为什么直接转换不合法

const char** 和 const void** 是两种不兼容的指针类型,C++不允许隐式转换,直接传递&d会编译失败。这是类型安全机制的限制:如果允许直接转换,可能通过const void**修改底层指针的类型,导致类型错误或绕过const限定。

同时reinterpret_cast也无法直接完成这一转换,因为C++标准限制了该转换符的适用场景,不能直接在指向不同指针类型的指针间转换。

合法转换方法(无需C风格转换)

方法1:先转换底层指针再传址

这是最安全、符合类型规范的方式:先将const char*隐式转换为const void*,再传递这个临时变量的地址给foo:

void foo(const void** v) {
}
int main() {
    const char* d = nullptr;
    const void* temp = d; // 隐式转换合法
    foo(&temp);
}

方法2:通过static_cast间接转换

如果必须直接传递原指针的地址,可以通过两次static_cast完成转换。这种方式合法但需谨慎,仅在确保不会通过const void**修改底层指针类型的场景下使用:

void foo(const void** v) {
}
int main() {
    const char* d = nullptr;
    foo(static_cast<const void**>(static_cast<void*>(&d)));
}

这里先将const char**转换为void*(任何指针类型都可转换为void*),再将void*转换为const void**,这两步转换均符合C++标准。

内容的提问来源于stack exchange,提问作者Afshin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:53:19