了解CComBSTR赋值运算符

了解CComBSTR赋值运算符

本文介绍了了解CComBSTR赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下:

  BSTR myBSTR = SysAllocString(LMYBSTR); 
CComBSTR myCComBSTR = myBSTR;

myCComBSTR $ c> myBSTR ,当它超出范围时释放它?或者它是否创建 myBSTR 的副本并产生内存泄漏,如果我不自由 myBSTR



如果这产生内存泄漏,什么是最有效的处理方式? ( myBSTR 将作为 BSTR 传递给函数,我想将它存储为<$ c $ code>实例创建一个独立的副本。您需要手动释放 myBSTR 以避免泄漏。



解决这种情况最简单的方法是跳过中间人 SysAllocString 函数

  CComBSTR myCComBSTR = LMYBSTR 

另一方面,如果你有一个 BSTR 并且想要拥有 CComBSTR 的所有者船,然后使用附加方法。此方法将资源的所有权从源 BSTR 转移到 CComBSTR 实例。

  CComBSTR myCComBSTR; 
myCComBSTR.Attach(myBSTR);


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

这篇关于了解CComBSTR赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 03:21