好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C++内存泄漏基础

C++内存泄漏基础

一段漂亮的代码必须考虑到内存泄漏的问题,而内存泄漏根本原因是因为你的程序在heap中分配的内存没有释放掉,当然没有释放掉的原因很多,最简单的就是你new完之后没有写delete,当然还有很多其他的原因,下面是我最近的一些新得。

    

#include <iostream>

 using   namespace   std;

  #define  true 1

 class   A
{
  private  :
      int   n;

  public  :
    A(  int  m){ cout<< "  A() is called\n  "  ;}
     ~A(){ cout<< "  ~A() is called\n  "  ;}
};

  int   main()
{
    cout << "  Enter into action scope\n  "  ;
      if ( true  )
    { 
        A * a= new  A( 1  );
    }
    cout << "  leave out action scope\n\n\n  "  ;


    cout << "  Enter into action scope\n  "  ;
      if ( true  )
    {
        A * b= new  A( 1  );
        delete b;
    } 
    cout << "  leave out action scope\n\n\n  "  ;
    
    
    cout << "  Enter into action scope\n  "  ;
      if ( true  )
    { 
        A c(  1  );
    }
    cout << "  leave out action scope\n  "  ;
      return   0  ;
} 

能过上面的代码已经运行结果可以知道,当你使用new来创建对象时,一定要记住delete掉对象,不要期望class的析构函数会自动调用,而第三种情况class的析构函数能自动调用,是因为对象c是局部变量,出了作用域就可以利用局部变量自动出栈,而调用class的析构函数。这个和局部变量只在作用域内起作用一脉相承。

但是也不要认为第二种的调用方式一定可以析构掉对象b,因为很多时候你可能没有到delete,而已经跳出了作用域,此时delete没有被调用到,那么对象中的动态分配的内存就有可能没有释放掉,所以如何保证delete一定可以被调用到是一个关键。

#include <iostream>

 using   namespace   std;

  #define  true 1

 class   A
{
  private  :
      int   n;

  public  :
    A(  int  m){ cout<< "  A() is called\n  "  ;}
     ~A(){ cout<< "  ~A() is called\n  "  ;}
};    

  int   main()
{   
    cout << "  Enter into action scope\n  "  ;
      while ( true  ) 
    {
        A * b= new  A( 1  );
          break  ;
        delete b;  
    } 
    cout << "  leave out action scope  "  ;

      return   0  ;

}

由上可以发现class的析构函数没有被调用,直接退出了循环,这个例子只是一个演示而已,因为有很多原因可能造成delete没有被调用到,比如异常被抛出,或者break,或者continue等等。。。。,所以如何保证delete被临幸很关键。但是如果不利用new来创建对象,那么就算提前退出循环,析构函数也会自动调。

#include <iostream>

 using   namespace   std;

  #define  true 1

 class   A
{
  private  :
      int   n;

  public  :
    A(  int  m){ cout<< "  A() is called\n  "  ;}
     ~A(){ cout<< "  ~A() is called\n  "  ;}
};    

  int   main()
{   
    cout << "  Enter into action scope\n  "  ;
      while ( true  ) 
    {
        A b(  1  ); 
          break  ;
    } 
    cout << "  leave out action scope\n  "  ; 
    
      return   0  ;
}  

所以将所有的资源放在对象里,可以防止内存泄漏。

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于C++内存泄漏基础的详细内容...

  阅读:41次