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

StackOverflow https://stackoverflow.com/questions/21169830

  •  28-09-2022
  •  | 
  •  

Pergunta

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?

Foi útil?

Solução

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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top