srajeshnkl
srajeshnkl

Reputation: 903

CComBSTR memory management

I am using CComBSTR in below scenario,

void MyDlg::OnTimer()
{

      ......

      CComBSTR statusString1 = ::SysAllocString(_T("Test"));

      ....

}

The timer will get executed with in each 5 seconds interval.

In the above case the meory is getting increased for each 5 seconds. As per my understanding the CComBSTR does the memory clean up when it goes out of scope. So the allocated memory has to be freed whenever the timer finishes. But its not.

I need to understand when the memory get freed when the CCOMBSTR is used.

Upvotes: 1

Views: 1451

Answers (1)

snowdude
snowdude

Reputation: 3874

Your use of CComBSTR is wrong. CComBSTR is making a copy of the allocated string NOT taking ownership of it. You can just initialize your CComBSTR like this:

CComBSTR statusString1( L"Test" );

If you want to take ownership of a previously allocated string do this:

BSTR bstrAlloc = ::SysAllocString(_T("Test"));
... Your Code ...
CComBSTR status;
status.Attach( bstrAlloc );

Then when the CComBSTR goes out of scope it will destroy the allocated string.

More info: I recommend having a look at the implementation of CComBSTR in atlcomcli.h (usually located in the C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\include folder). It's not complicated.

Upvotes: 4

Related Questions