天天看点

BSTR在使用过程中为什么会内存泄露呢

http://topic.csdn.net/t/20030429/20/1723435.html

Don 't   use   BSTR,   use   ATL 's   _bstr_t   or   MFC 's   CComBSTR   instead   to   avoid   memory   leak.

Here   is   why:

Case   1   with   memory   leak:

line   1:   BSTR   Bstr;

line   2:   pSomeObject-> Get_SomeString(   &Bstr   );

line   3:   _bstr_t   AtlBstr;

line   4:   AtlBstr   =   Bstr;       //   Memory   leak   here!!!

In   line   1,   when   Bstr   is   declared   and   initialized,   a   call   to   SysAllocString   is   automatically   made   when   creating   the   Bstr   variable,   but   it   is   never   freed   later,   so   it   causes   memory   leak.

Case   2   without   memory   leak:   (Solution   1)

line   1:   BSTR   Bstr;

line   2:   pSomeObject-> Get_SomeString(   &Bstr   );

line   3:   _bstr_t   AtlBstr(   Bstr,   FALSE   );   //   avoid   a   memory   leak

(Solution   2)

line   1:   BSTR   Bstr;

line   2:   pSomeObject-> Get_SomeString(   &Bstr   );

line   3:   _bstr_t   AtlBstr;

line   4:   AtlBstr   =   Bstr;  

line   5:   ::SysFreeString(   Bstr   );   //   free   that   memory.

解释:

最重要的要理解一点,使用BSTR就象使用 c语言中的内存指针一样,分配了,必须在合适的地方释放 

因此,记住,对应普通的BSTR,不能进行一般的赋值操作,就象你对已经分配了空间的指针,不能随便再次赋值一样。

楼上说的对,可以使用其他的辅助的包装类,避免这些问题。

但实际应用中,有许多更复杂的情况,简单地使用以上的方法不能解决

所以,还是认真掌握其根本概念吧 

BSTR是一个字符串指针,声明的时候不会分配内存,当然需要使用者分配、释放内存,就像C里的char一样处理;而_bstr_t是封装了BSTR的类,它在析构函数中会释放该类变量所占的内存,所以无需使用者自己释放。