Share via


Allocazione e rilascio della memoria per un oggetto BSTR

Quando si creano BSTRoggetti e li si passa tra oggetti COM, è necessario occuparsi del trattamento della memoria usata per evitare perdite di memoria. Quando un oggetto rimane all'interno di BSTR un'interfaccia, è necessario liberarne la memoria al termine dell'operazione. Tuttavia, quando un oggetto BSTR passa da un'interfaccia, l'oggetto ricevente assume la responsabilità della gestione della memoria.

In generale, le regole per l'allocazione e il rilascio della memoria allocata per BSTRs sono le seguenti:

  • Quando si chiama in una funzione che prevede un BSTR argomento, è necessario allocare la memoria per l'oggetto BSTR prima della chiamata e rilasciarla in un secondo momento. Ad esempio:

    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);
    }
    
  • Quando si chiama in una funzione che restituisce un oggetto BSTR, è necessario liberare manualmente la stringa. Ad esempio:

    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);
    
  • Quando si implementa una funzione che restituisce un BSTRoggetto , allocare la stringa ma non liberarla. La funzione ricevente rilascia la memoria. Ad esempio:

    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);
    }
    

Vedi anche

Stringhe (ATL/MFC)
CStringT::AllocSysString
SysAllocString
SysFreeString