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 calledn";}
    ~A(){ cout<<"~A() is calledn";}
};

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


    cout<<"Enter into action scopen";
    if(true)
    {
        A* b=new A(1);
        delete b;
    } 
    cout<<"leave out action scopennn";


    cout<<"Enter into action scopen";
    if(true)
    { 
        A c(1);
    }
    cout<<"leave out action scopen";
    return 0;
}

C++内存泄漏基础1

能过上面的代码已经运行结果可以知道,当你使用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 calledn";}
    ~A(){ cout<<"~A() is calledn";}
};    

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

    return 0;
}

C++内存泄漏基础1

由上可以发现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 calledn";}
    ~A(){ cout<<"~A() is calledn";}
};    

int main()
{   
    cout<<"Enter into action scopen";
    while(true) 
    {
        A b(1); 
        break;
    } 
    cout<<"leave out action scopen"; 

    return 0;
}

C++内存泄漏基础1

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

原文链接: https://www.cnblogs.com/GODYCA/archive/2013/01/09/2853793.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/74985

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午4:40
下一篇 2023年2月9日 下午4:40

相关推荐