• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
张纯睿
博客园    首页    新随笔    联系   管理    订阅  订阅

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

posted @ 2010-12-29 09:52  张纯睿  阅读(256)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3