sashoalm
sashoalm

Reputation: 79447

ATL/COM: Why does CComSafeArray::GetCount() throw an exception for an empty array?

I'm using the ATL CComSafeArray class, but it seems that GetCount() will throw an exception if the array is empty, for example this code throws an exception:

CComSafeArray<MyStruct> array;
// array.Add(item); // There won't be an exception if I uncomment this line.
array.GetCount();

This is the code of the constructor and GetCount() (from ATL sources):

CComSafeArray() throw() : m_psa(NULL)
{
}
ULONG GetCount(UINT uDim = 0) const
{
    ATLASSUME(m_psa != NULL);
    ATLASSERT(uDim < GetDimensions());
    LONG lLBound, lUBound;
    HRESULT hRes = SafeArrayGetLBound(m_psa, uDim+1, &lLBound);
    ATLASSERT(SUCCEEDED(hRes));
    if(FAILED(hRes))
        AtlThrow(hRes);
    hRes = SafeArrayGetUBound(m_psa, uDim+1, &lUBound);
    ATLASSERT(SUCCEEDED(hRes));
    if(FAILED(hRes))
        AtlThrow(hRes);
    return (lUBound - lLBound + 1);
}

As you can see, the constructor gives a NULL value to m_psa, and in GetCount(), this causes SafeArrayGetLBound() to return an error HRESULT, which causes AtlThrow() to be called.

But I don't understand why GetCount() should throw an exception if the array is empty. Is that the expected behavior?

Upvotes: 1

Views: 997

Answers (1)

Tony Lee
Tony Lee

Reputation: 5632

You have an unbound wrapper for a SAFEARRAY, not an empty array.

If you want an empty SAFEARRAY you can declare one:

CComSafeArray<MyStruct> array((ULONG)0);

Upvotes: 3

Related Questions