Search code examples
c++comatl

When CComCriticalSection::Lock may return E_FAIL


MSDN (https://msdn.microsoft.com/en-us/library/04tsf4b5.aspx) says:

Return Value

Returns S_OK on success, E_OUTOFMEMORY or E_FAIL on failure.

What failure might be with acquiring lock?


Solution

  • It looks like it'll never return that. The references to E_FAIL and E_OUTOFMEMORY are likely standard comments wherever methods return an HRESULT. This method likely returns an HRESULT for consistency with other methods and/or compatibility with other ATL classes.

    Here is the code for CComCriticalSection in the vc140 (2017) toolset. Previous toolsets back to vc90 (2008) have similarly simple Lock() methods. The only changes between 2008 and 2017 were the addition of the SAL attributes _Success_ and _Acquires_lock_, which have no functional impact (they expand to nothing). I cannot comment for toolsets prior to 2008.

    class CComCriticalSection
    {
    public:
        CComCriticalSection() throw()
        {
            memset(&m_sec, 0, sizeof(CRITICAL_SECTION));
        }
    
        ~CComCriticalSection()
        {
        }
    
        _Success_(1) _Acquires_lock_(this->m_sec) HRESULT Lock() throw()
        {
            EnterCriticalSection(&m_sec);
            return S_OK;
        }
        _Success_(1) _Releases_lock_(this->m_sec) HRESULT Unlock() throw()
        {
            LeaveCriticalSection(&m_sec);
            return S_OK;
        }
        HRESULT Init() throw()
        {
            HRESULT hRes = S_OK;
            if (!_AtlInitializeCriticalSectionEx(&m_sec, 0, 0))
            {
                hRes = HRESULT_FROM_WIN32(GetLastError());
            }
    
            return hRes;
        }
    
        HRESULT Term() throw()
        {
            DeleteCriticalSection(&m_sec);
            return S_OK;
        }
        CRITICAL_SECTION m_sec;
    };