04~C++智能指针

1. 智能指针引入

有缺陷的代码设计

#include <iostream>
#include <string>

using namespace std;
int demo(void) {
 	string* tmp  = new string;
 	bool condition = false;
 	/*do something, condition may become true*/
 	if(condition){
 	    //条件满足时,异常抛出前存在未释放的内存资源
 		throw (tmp);
 	}
 	delete tmp;
 	return 0;
}
int main(void) 
{
return 0;
}

手动弥补以上设计缺陷:
依靠手工完成缺陷补救存在风险,毕竟程序员头脑风暴中充斥各种信息,风险被遗忘是很常见的

#include <iostream>
#include <string>

using namespace std;
int demo(void) {
 	string* tmp  = new string;
 	bool condition = false;
 	/*do something, condition may become true*/
 	if(condition){
 	    //条件满足时,异常抛出前存在未释放的内存资源
 	    delete tmp;
 		throw (tmp);
 	}
 	delete tmp;
 	return 0;
}
int main(void) 
{
return 0;
}

2. 智能指针

智能指针三种形式
auto_ptr C++98 标准
shared_ptr
unique_ptr

2.1 使用auto_ptr

优化:不再需要手动释放动态资源

#include <iostream>
//to use smart ptr
#include <memory>
#include <string>

using namespace std;
int demo(void) {
 	auto_ptr<string> tmp (new string);
 	bool condition = false;
 	/*do something, condition may become true*/
 	if(condition){
 		throw (tmp);
 	}
 	return 0;
}
int main(void) {
demo();
return 0;
}

2.2 unique_ptr

auto_ptr 缺陷:悬挂指针.
编译命令添加 std=c++11

#include <iostream>
//to use smart ptr
#include <memory>
#include <string>

using namespace std;
int demo(void) {
 	unique_ptr<string> tmp (new string ("hello"));
 	unique_ptr<string> tmp2;
 	/*这里会造成编译错误*/
 	tmp2 = tmp;
 	cout << *tmp2 << endl;
 	cout << *tmp <<endl;
 	bool condition = false;
 	/*do something, condition may become true*/
 	if(condition){
 		throw (tmp);
 	}
 	return 0;
}
int main(void) {
demo();
return 0;
}

输出:
hello
Segmentation fault (core dumped)

2.3. C++11 标准

新标准丢弃了auto_ptr ,原因在于其存在缺陷

2.4 shared_ptr

shared 指针允许多个职能指针持有一块资源,并在引用计数为0的时候,析构资源

#include <iostream>
//to use smart ptr
#include <memory>
#include <string>

using namespace std;
int demo(void) {
 	shared_ptr<string> tmp (new string ("hello"));
 	shared_ptr<string> tmp2;
 	/*对象引用计数+1*/
 	tmp2 = tmp;
 	cout << *tmp2 << endl;
 	cout << *tmp <<endl;
 	bool condition = false;
 	/*do something, condition may become true*/
 	if(condition){
 		throw (tmp);
 		
 	}
 	return 0;
}
int main(void) {
demo();
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值