• C++内存泄漏基础1


    一段漂亮的代码必须考虑到内存泄漏的问题,而内存泄漏根本原因是因为你的程序在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;
    } 

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

  • 相关阅读:
    【转载】#349
    【转载】#346
    【转载】#344
    【转载】#336
    【转载】#335
    【转载】#330
    【转载】#324
    win2008远程桌面卡顿和上传慢的解决方法
    sql2005导出数据字典
    第03组 Alpha冲刺 (6/6)
  • 原文地址:https://www.cnblogs.com/GODYCA/p/2853793.html
Copyright © 2020-2023  润新知