Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

AtlThrow inside a COM method implementation

56 views
Skip to first unread message

Giovanni Dicanio

unread,
Oct 12, 2009, 4:36:05 AM10/12/09
to
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

Igor Tandetnik

unread,
Oct 12, 2009, 8:21:33 AM10/12/09
to
Giovanni Dicanio wrote:
> So, in case of errors, AtlThrow() is called.
> Reading the documentation, if my understanding is correct, AtlThrow
> throws a CAtlException in ATL projects.

If _ATL_NO_EXCEPTIONS macro is not defined. Otherwise, it raises a structured exception with RaiseException.

> So, should the original code posted above be modified, wrapping the
> CComSafeArray constructor call in a try/catch( CAtlException & )
> block?

Either that, or write it as

CComSafeArray<VARIANT> data;
HRESULT hr = data.Create(bounds, _countof(bounds));

> Or does ATL have some C++ template "magic" to automatically return an
> HRESULT value when AtlThrow is called?

Not to my knowledge.
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not necessarily a good idea. It is hard to be sure where they are going to land, and it could be dangerous sitting under them as they fly overhead. -- RFC 1925

Giovanni Dicanio

unread,
Oct 12, 2009, 10:59:49 AM10/12/09
to
Thank you,
Giovanni


"Igor Tandetnik" <itand...@mvps.org> ha scritto nel messaggio
news:O8QWLazS...@TK2MSFTNGP02.phx.gbl...

0 new messages