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;
}