作用
- 管理指针,避免申请的内存空间在函数结束时忘记释放,造成内存泄漏
四种智能指针
(1)auto_ptr
- 基本废弃,缺点是没有资源共享
auto_ptr<int> ap1(new int);
auto_ptr<int> ap2 = ap1;
std::cout << "ap1 : " << ap1.get() << ", ap2 : " << ap2.get() << std::endl;
auto_ptr<int> ap3(ap2);
std::cout << "ap2 : " << ap2.get() << ", ap3 : " << ap3.get() << std::endl;
输出如下:
ap1 : 0, ap2 : 0x181ec20
ap2 : 0, ap3 : 0x181ec20
(2)unique_ptr
- 禁止拷贝和赋值
unique_ptr<int> up1(new int);
//unique_ptr<int> up2 = up1; error
//unique_ptr<int> up3(up1); error
(3)shared_ptr
- 资源共享,多个指针可以指向同一内存,根据引用计数记录
shared_ptr<int> sp1(new int);
std::cout << "refrence count : " << sp1.use_count() << std::endl;
shared_ptr<int> sp2 = sp1;
std::cout << "refrence count : " << sp1.use_count() << std::endl;
shared_ptr<int> sp3(sp1);
std::cout << "refrence count : " << sp1.use_count() << std::endl;
sp2.reset();
std::cout << "refrence count : " << sp1.use_count() << std::endl;
sp3.reset();
std::cout << "refrence count : " << sp1.use_count() << std::endl;
输出如下:
refrence count : 1
refrence count : 2
refrence count : 3
refrence count : 2
refrence count : 1
(4)weak_ptr
- 不改变引用计数
weak_ptr<int> wp1(sp1);
std::cout << "refrence count : " << sp1.use_count() << std::endl;
wp1.reset();
std::cout << "refrence count : " << sp1.use_count() << std::endl;
输出如下:
refrence count : 1
refrence count : 1