Share via


配置和釋放 的記憶體 BSTR

當您建立 BSTR s 並在 COM 物件之間傳遞它們時,您必須小心處理所使用的記憶體,以避免記憶體流失。 BSTR當 保留在介面內時,您必須在完成時釋放其記憶體。 不過,當 傳出介面時 BSTR ,接收物件會負責其記憶體管理。

一般而言,配置和釋放配置 BSTR 給 s 之記憶體的規則如下:

  • 當您呼叫預期引數的 BSTR 函式時,您必須在呼叫之前配置 的記憶體 BSTR ,並在之後釋放它。 例如:

    HRESULT CMyWebBrowser::put_StatusText(BSTR bstr)
    

     

    // shows using the Win32 function 
    // to allocate memory for the string: 
    BSTR bstrStatus = ::SysAllocString(L"Some text");
    if (bstrStatus != NULL)
    {
       pBrowser->put_StatusText(bstrStatus);
       // Free the string:
       ::SysFreeString(bstrStatus);
    }
    
  • 當您呼叫傳回 BSTR 的函式時,您必須自行釋放字串。 例如:

    HRESULT CMyWebBrowser::get_StatusText(BSTR* pbstr)
    

     

    BSTR bstrStatus;
    pBrowser->get_StatusText(&bstrStatus);
    
    // shows using the Win32 function 
    // to free the memory for the string: 
    ::SysFreeString(bstrStatus);
    
  • 當您實作傳回 BSTR 的函式時,請配置字串,但不釋放它。 接收函式會釋放記憶體。 例如:

    HRESULT CMyClass::get_StatusText(BSTR* pbstr)
    {
       try
       {
          //m_str is a CString in your class
          *pbstr = m_str.AllocSysString();
       }
       catch (...)
       {
          return E_OUTOFMEMORY;
       }
    
       // The client is now responsible for freeing pbstr.
       return(S_OK);
    }
    

另請參閱

字串 (ATL/MFC)
CStringT::AllocSysString
SysAllocString
SysFreeString