AtlThrow inside a COM method implementation
Considering code something like this (the implementation of some COM
interface method using ATL):
<code>
HRESULT CSomeClass::DoSomething( /*[in,out]*/ long* count,
/*[out]*/ SAFEARRAY** result)
{
if (count == NULL || result == NULL)
{
return E_POINTER;
}
CComSafeArrayBound bounds[2] =
{
...
};
CComSafeArray<VARIANT> data(bounds, _countof(bounds));
...
...
*result = data.Detach();
...
return S_OK;
}
</code>
I think (but I'm not sure) that there is a problem in the use of
CComSafeArray constructor above.
In fact, if some error occurrs during constructor, what does happen?
Spelunking in CComSafeArray constructor overload code, I read in
<atlsafe.h>:
<code>
// create SAFEARRAY where number of elements = ulCount
explicit CComSafeArray(ULONG ulCount, LONG lLBound = 0) : m_psa(NULL)
{
CComSafeArrayBound bound(ulCount, lLBound);
HRESULT hRes = Create(&bound);
if (FAILED(hRes))
AtlThrow(hRes);
}
</code>
So, in case of errors, AtlThrow() is called.
Reading the documentation, if my understanding is correct, AtlThrow throws a
CAtlException in ATL projects.
So, should the original code posted above be modified, wrapping the
CComSafeArray constructor call in a try/catch( CAtlException & ) block?
e.g.
<code>
HRESULT hr = S_OK;
try
{
... <above code> ...
}
catch (CAtlException & e)
{
hr = (HRESULT)e;
}
return hr;
</code>
Or does ATL have some C++ template "magic" to automatically return an
HRESULT value when AtlThrow is called?
Thanks in advance,
Giovanni