0

I have following code:

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

It is correctly compiled. But I need to replace (LPVOID*)&psl by *_cast. What cast I must use?

static_cast<LPVOID*>(&psl) generates an error (in MSVC 2013).

Will it be correct to use reinterpret_cast<LPVOID*>(&psl)?

vladon
  • 8,158
  • 2
  • 47
  • 91
  • `reinterpret_cast` is essentially equivalent to C-style cast. So if you intend to use it, then just be sure you know what you're doing. – barak manos Apr 23 '15 at 10:55
  • @barakmanos is there any way to do this cast with `static_cast`? – vladon Apr 23 '15 at 10:57
  • 1
    You can do `static_cast(static_cast(&psl))`. – barak manos Apr 23 '15 at 11:00
  • While the double-static_cast is correct and will work, there's really no reason to use it. You can always double-static_cast anything that you'd otherwise have to reinterpert_cast, so you might as well just reinterpret_cast it. – cooky451 Apr 23 '15 at 11:02
  • 1
    @cooky451: That was precisely what I had in mind to write down as the remaining of that comment ("might as well just use `reinterpret_cast`")... But I was a little lazy adding it... – barak manos Apr 23 '15 at 11:05

2 Answers2

1

Yes, reinterpret_cast is the correct choice. Usually, the conversion from a type* to a void* should be done implicit, while the conversion from a void* to a type* should be done with a static_cast. But in your case you're converting from a type** to a void**, which leaves you no choice but to use a reinterpret_cast. It is still somewhat "safer" than a c-style cast though, because you cannot cast away constness.

cooky451
  • 3,460
  • 1
  • 21
  • 39
  • You and @malhotraprateek answered simultaneously on the same minute :-) Thank you. I mark its answer as answer for giving him reputation (you are already have much :) ) – vladon Apr 23 '15 at 11:29
1

I think you may have to use the reinterpret_cast, as the CoCreateInstance function's last parameter is used for output purposes. See this link: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686615(v=vs.85).aspx

So whether you do a C-Style cast or use the reinterpret_cast, the function just wants to put a pointer value into your variable "psl" after making an object in heap.