Allocating and Releasing Memory for a BSTR

來源:互聯網
上載者:User

 

When you create BSTRs and pass them between COM objects, you must take care in treating the memory they use in order to avoid memory leaks. When a BSTR stays within an interface, you must free its memory when you are done with it. However, when a BSTR passes out of an interface, the receiving object takes responsibility for its memory management.

In general, the rules for allocating and releasing memory allocated for BSTRs are as follows:

1. When you call into a function that expects a BSTR argument, you must allocate the memory for the BSTR before the call and release it afterwards. For example:

HRESULT CMyWebBrowser::put_StatusText(BSTR bstr);

// shows using the Win32 function<br />// to allocate memory for the string:<br />BSTR bstrStatus = ::SysAllocString(L"Some text");<br />if (bstrStatus != NULL)<br />{<br /> pBrowser->put_StatusText(bstrStatus);<br /> // Free the string:<br /> ::SysFreeString(bstrStatus);<br />}

2. When you call into a function that returns a BSTR, you must free the string yourself. For example:

HRESULT CMyWebBrowser::get_StatusText(BSTR* pbstr);

BSTR bstrStatus;<br />pBrowser->get_StatusText(&bstrStatus);<br />// shows using the Win32 function<br />// to free the memory for the string:<br />::SysFreeString(bstrStatus);

3. When you implement a function that returns a BSTR, allocate the string but do not free it. The receiving the function releases the memory. For example:

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

 

 

 

http://msdn.microsoft.com/en-us/library/xda6xzx7.aspx

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.