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

  • 相关阅读:
    ASP.NET MVC EF 连接数据库(一)-----Database First
    设计模式——策略模式
    设计模式——简单工厂模式
    分享一些技术大牛的博客
    有货双中心双活架构实践
    分布式协调服务Zookeeper应用场景
    分布式服务框架资料汇总
    Java线程池ThreadPoolExecutor解析
    服务注册中心Zookeeper和Eureka比较
    JVM内存结构、垃圾回收及性能调优
  • 原文地址:https://www.cnblogs.com/carl2380/p/1919422.html
Copyright © 2011-2022 走看看