Search code examples
c++mfccomatlbstr

Reassigning CComBSTR, memory leak?


As it's written in the MSDN documentation CComBSTR::operator= creates a copy of src. So when I write

someCComBSTR = std::to_wstring(someVal).c_str();

I will have a copy of the temporary and everything is ok. But I haven't found what happens with the previous value, will it be freed or rewritten, or I first should manually empty my CComBSTR object?


Solution

  • CComBSTR is defined in the header atlcomcli.h in Visual Studio's atlmfc/include directory. All assignment operators (operator=) release the currently owned data by calling SysFreeString (with some exceptions that aren't interesting here).

    The line of code posted in the question will not leak any resources. It is invoking the following assignment operator for CComBSTR (comments added for clarity):

    CComBSTR& operator=(_In_opt_z_ LPCOLESTR pSrc)
    {
        // Prevent self-assignment
        if (pSrc != m_str)
        {
            // Free currently owned resources
            ::SysFreeString(m_str);
            if (pSrc != NULL)
            {
                // Create copy of pSrc and take ownership
                m_str = ::SysAllocString(pSrc);
                // Error handling
                if (!*this)
                {
                    AtlThrow(E_OUTOFMEMORY);
                }
            }
            else
            {
                // Clear instance data if pSrc is a null pointer
                m_str = NULL;
            }
        }
        return *this;
    }