C++中典型的内存泄露

一、典型的一个内存泄露的代码例子

#include<iostream>
using namespace std;
class A
{
public:
A (int i){this->i=i;cout<<"costr"<<endl;}
int getI();
A(A&a)
{
this->i=a.i;
cout<<"copy"<<endl;
}
~A(){cout<<"destory"<<endl;}
private:
int i;
};
A::getI()
{
return this->i;
}
A fuct()
{
A *a = new A(12);
return *a;
}
void main()
{
A *a = &fuct();
cout<<a->getI()<<endl;
}


我们可以看到只调用了一次析构函数,由于在fuct函数中,使用了new 关键字创建了一个堆中空间,在函数运行结束时,

返回的是一个副本,调用的复制构造函数返回,因此在fuct函数中创建的一个堆中空间就无法释放,因此出现了内存泄露。

二、避免出现内存泄露的改进

#include<iostream>
using namespace std;
class A
{
public:
A (int i){this->i=i;cout<<"costr"<<endl;}
int getI();
A(A&a)
{
this->i=a.i;
cout<<"copy"<<endl;
}
~A(){cout<<"destory"<<endl;}
private:
int i;
};
A::getI()
{
return this->i;
}
A &fuct()
{
A *a = new A(12);
return *a;
}
void main()
{
A &a = fuct();
A *p=&a;
delete p;
cout<<a.getI()<<endl;
}


这样就可以避免内存的泄露,但是会出现一个致命的错误,就是会出现一个空的引用存在。

三、哪里创建哪里删除原则

在使用,函数中如果是要使用返回创建的指针,可以在调用的该方法的地方前创建,调用结束后,在释放该快内存。

修改代码如下:

#include<iostream>
using namespace std;
class A
{
public:
A (int i){this->i=i;cout<<"costr"<<endl;}
int getI();
void setI(int x)
{
this->i=x;
}
A(A&a)
{
this->i=a.i;
cout<<"copy"<<endl;
}
~A(){cout<<"destory"<<endl;}
private:
int i;
};
A::getI()
{
return this->i;
}
A &fuct(A &a)
{
a.setI(56);
return a;
}
void main()
{
A *a= new A(15);
fuct(*a);
cout<<a->getI()<<endl;
delete a;
}

就可以做到在函数中不进行创建空间,在main函数中创建,在main函数中释放。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值