0

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?

Name
  • 37
  • 4
  • Not sure what you mean by the 'temporary'. The version of the `=` operator you are using is taking an `LPCSTR` as its argument and assigning a copy of that to the `m_str` member of your destination `BSTR` object. Presumably, that will be freed when `someCComBSTR` is destroyed. – Adrian Mole Jul 12 '21 at 11:42
  • if the class is not broken you can assume that it correctly manages its resources. Did you observe some memory leak? Kind of relevant: https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three – 463035818_is_not_an_ai Jul 12 '21 at 11:42
  • @463 Visual Studio comes with several `BSTR` wrappers (`CComBSTR`, `_bstr_t`, etc.). They all behave slightly different with respect to resource management. Making assumptions is terrible advice. – IInspectable Jul 12 '21 at 11:54

1 Answers1

4

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;
}
IInspectable
  • 46,945
  • 8
  • 85
  • 181