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的类,它在析构函数中会释放该类变量所占的内存,所以无需使用者自己释放。
                       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值