【问题标题】:cast pointer to pointer as LPVOID*将指针转换为 LPVOID*
【发布时间】:2015-07-01 12:10:45
【问题描述】:

我有以下代码:

IShellLink* psl;
HRESULT hres = CoCreateInstance(
    CLSID_ShellLink, 
    NULL, 
    CLSCTX_INPROC_SERVER, 
    IID_IShellLink, 
    (LPVOID*)&psl);

已正确编译。但我需要将(LPVOID*)&psl 替换为*_cast。我必须使用什么演员表?

static_cast<LPVOID*>(&psl) 生成错误(在 MSVC 2013 中)。

使用reinterpret_cast<LPVOID*>(&psl)会正确吗?

【问题讨论】:

  • reinterpret_cast 本质上等同于 C 风格的强制转换。因此,如果您打算使用它,请确保您知道自己在做什么。
  • @barakmanos 有什么办法可以用static_cast 来做这个演员吗?
  • 你可以做static_cast<LPVOID*>(static_cast<LPVOID>(&psl))
  • 虽然 double-static_cast 是正确的并且会起作用,但实际上没有理由使用它。你总是可以对任何你必须 reinterpert_cast 的东西加倍 static_cast,所以你最好只是 reinterpret_cast 它。
  • @cooky451:这正是我想写下来的评论的剩余部分(“不妨只使用reinterpret_cast”)......但我有点懒惰添加它...

标签: c++ pointers casting reinterpret-cast static-cast


【解决方案1】:

是的,reinterpret_cast 是正确的选择。通常,从 type* 到 void* 的转换应该是隐式的,而从 void* 到 type* 的转换应该使用 static_cast 来完成。但是在您的情况下,您正在从 type** 转换为 void**,这让您别无选择,只能使用 reinterpret_cast。不过,它仍然比 c 风格的演员“更安全”,因为你不能放弃 constness。

【讨论】:

  • 您和@malhotraprateek 在同一分钟同时回答 :-) 谢谢。我将它的答案标记为给予他声誉的答案(你已经有很多了:))
【解决方案2】:

我认为您可能必须使用 reinterpret_cast,因为 CoCreateInstance 函数的最后一个参数用于输出目的。 见此链接:https://msdn.microsoft.com/en-us/library/windows/desktop/ms686615(v=vs.85).aspx

因此,无论您是进行 C 样式转换还是使用 reinterpret_cast,该函数都只想在堆中创建对象后将指针值放入变量“psl”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 2012-10-24
    • 2017-02-12
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多