How can I check that [out] parameters in COM can be used?
Officially, you shouldn't use parameters [out]
from COM functions if the function fails, which means there are (at least) three ways to see if a parameter can be used [out]
.
Consider the following interface
interface IFoo : IUnknown {
HRESULT GetOtherFoo([out] IFoo** ppFoo);
HRESULT Bar();
};
Which of the following methods would you recommend using it?
1. Check the return value
CComPtr<IFoo> other;
HRESULT hr = foo->GetOtherFoo(&other);
if (SUCCEEDED(hr))
other->Bar();
This makes me a little bit nervous, as a mistake in IFoo
could lead to dereferencing of the pointer NULL
.
2. Check the output parameter
It depends on the fact that if the method fails, it should not change any of the parameters [out]
(if the parameter is changed <==> it is safe to use it).
CComPtr<IFoo> other;
foo->GetOtherFoo(&other);
if (other)
other->Bar();
Note that this kind of thing doesn't matter, CComPtr
destructor will call Release
if the pointer is not NULL
, so it cannot be garbage.
3. Paranoid way, check how
CComPtr<IFoo> other;
HRESULT hr = foo->GetOtherFoo(&other);
if (SUCCEEDED(hr) && other)
other->Bar();
It's a little wordy in my opinion.
PS See related question .
source to share
COM server methods that return an HRESULT but some of their output parameters are NULL are not very common. There are several cases (IClientSecurity :: QueryBlanket comes to mind) where this is used, but usually the client can expect all output parameters to be non-NULL if the method returns successfully.
It is, after all, a question of how this document is documented. However, in the default case, I believe that 1. be the safe way to go.
source to share