C++智能指针入门之unique_ptr

智能指针解决了程序员忘记释放对象,导致内存遗漏的问题
如下:

#include <iostream>
#include <memory>
#include <unistd.h>
using namespace std;

class A18 {
public:
	A18() {
		cout << "default constructor" << endl;
	}
	int say() {
		cout << "A say:" << endl;
		return 0;
	}
	~A18() {
		cout << "Destructor called" << endl;
	}
};

void f0() {
	A18 *a=new A18();
	a->say();
}

int main() {
	f0();
	sleep(2);
	cout << "end" << endl;
	return 0;
}


我们在f0()方法中new了一个A18的对象,但是忘记释放。
主程序在调用f0之后2秒退出,控制台打印如下:

default constructor
A say:
end

可以发现没有调用A18的析构函数,发生了内存泄露。

接下来我们使用

#include <iostream>
#include <memory>
#include <unistd.h>
using namespace std;

class A18 {
public:
	A18() {
		cout << "default constructor" << endl;
	}
	int say() {
		cout << "A say:" << endl;
		return 0;
	}
	~A18() {
		cout << "Destructor called" << endl;
	}
};

void f0() {
	unique_ptr<A18> a(new A18());
	a->say();
}

int main() {
	f0();
	sleep(2);
	cout << "end" << endl;
	return 0;
}

编译: g++ a.cpp -o a
运行 : ./a

继续运行看打印结果:

default constructor
A say:
Destructor called
end

完美,A18析构函数被调用,说明对象被释放。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值