gpt4 book ai didi

c++ - static_cast 一个 void* 指针可以吗

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:03:43 29 4
gpt4 key购买 nike

例如提议map<int,void*>hold其中 void*总是存储来自 classA 的指针稍后通过 static_cast 将其投回是否安全?

classA* ptr = static_cast<classA*>( holditerator->second );

原因void*使用是因为hold是在某些不知道什么的 cpp 文件使用的 header 上定义的类的成员 classA是。我必须包括 classA 的标题这些 cpp 文件的定义由于许多原因而无法完成。

最佳答案

是的,static_cast 在那种情况下是可以的,并且是正确的使用方式。

不过,我不得不问您为什么不首先存储 classA* 指针。如果你想将派生类指针放入其中,那么注意,你需要将派生类指针向上转换(隐式或显式)到 classA* 之前 你把它们放到 map 上。

但即使您也将派生类指针放入映射中,基类指针就足够了,因为派生类指针可以隐式转换为基类指针。

The reason void* is used is because hold is member of a class define on a header used by some cpp files which don't know what classA is.

这可能是防止分层违规的正当理由。

I would have to include the header of classA definitions on these cpp files which can't be done by many reasons.

您的情况很可能没有必要。前向声明就足够了。如果 header 知道放入 map 的内容,但只是想避免包含额外的 header ,这就是要走的路。

关于c++ - static_cast 一个 void* 指针可以吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12120900/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com