智能指针
前言
智能指针是cpp11新特性中重要的部分,共有到三种智能指针,shared_ptr,unique_ptr,weak_ptr,本文介绍了他们的概念,注意事项和使用示例
1 共享智能指针
1.1 概念
智能指针是用来自动释放堆区的内存,共享智能指针可以使得多个智能指针指向同一块内存
1.2 注意
- 智能指针的实现是内部实现了一个计数器,当该地址被智能指针指向时计数器+1,当计数器为0时,便会调用删除器删除该堆区内存
1.3 代码实现
#include<iostream>
using namespace std;
class test{
public:
void print(){
cout<<"this funcation has been called"<<endl;
}
~test(){
cout<<"this object is been deleted"<<endl;
}
};
int main(){
shared_ptr<test> p1(new test);
cout<<p1.use_count()<<endl;
shared_ptr<test> p2(p1);
cout<<p1.use_count()<<endl;
shared_ptr<test> p3 = make_shared<test>();
shared_ptr<test> p4(p3);
cout<<p4.use_count()<<endl;
p3.reset(new test);
cout<<p3.use_count()<<endl;
sleep(500);
}
2 独占智能指针
1.1 概念
只能使用单独的智能指针管理指定的内存
1.2 注意
- 独占智能指针绑定删除器和共享智能指针并不相同
1.3 代码实现
#include<iostream>
using namespace std;
class test{
public:
void print(){
cout<<"this funcation has been called"<<endl;
}
~test(){
cout<<"this object has been deleted"<<endl;
}
};
int main(){
unique_ptr<test> p1(new test);
//unique_ptr<test> p2(p1) error
p1.reset(new test);
unique_ptr<test,function<void(test* t)>> p2(new test,[](test* t){
delete t;
});
sleep(500);
}
3 弱引用智能指针
1.1 概念
弱引用智能指针并不会管理内存,而是对共享智能指针的操作补充
1.2 注意
1.3 代码实现
#include<iostream>
using namespace std;
class test{
public:
void print(){
cout<<"this funcation has been called"<<endl;
}
~test(){
cout<<"this object has been deleted"<<endl;
}
};
int main(){
shared_ptr<test>p1(new test);
weak_ptr<test>p2(p1);
cout<<p2.use_count()<<endl;
shared_ptr<test>p3(p2.lock());
cout<<p2.use_count()<<endl;
cout<<p2.expired()<<endl;
p3.reset();
p1.reset();
cout<<p2.expired()<<endl;
p2.reset();
sleep(500);
}