开发者

Understanding CComBSTR assignment operators

开发者 https://www.devze.com 2023-01-13 11:01 出处:网络
Say I have the following: BSTR myBSTR = SysAllocString( L\"MYBSTR\" ); CComBSTR myCComBSTR = myBSTR; Does myCComBSTR take ownership of myBSTR and free it when it goes out of scope? Or does it make

Say I have the following:

BSTR myBSTR = SysAllocString( L"MYBSTR" );
CComBSTR myCComBSTR = myBSTR;

Does myCComBSTR take ownership of myBSTR and free it when it goes out of scope? Or does it make a copy of myBST开发者_StackOverflow中文版R and produce a memory leak if i dont free myBSTR?

If this produces a memory leak, what's the most efficient way of handling this? (myBSTR will be passed in to a function as a BSTR and i want to store it as a CComBSTRinternally)


In this case the CComBSTR instance creates an independent copy. You will need to manually free myBSTR to avoid a leak.

The simplest approach to fix this scenario is to skip the middle man SysAllocString function

CComBSTR myCComBSTR = L"MYBSTR";

On the other hand if you have a BSTR and want to have a CComBSTR take owner ship of it then use attach method. This method transfers ownership of the resource from the source BSTR to the CComBSTR instance.

CComBSTR myCComBSTR;
myCComBSTR.Attach(myBSTR);
0

精彩评论

暂无评论...
验证码 换一张
取 消