智能指针模版类

有三个智能指针,auto_ptr(弃用)、unique_ptr、shared_ptr.
智能指针可以自动跟踪动态内存,在其过期时自动释放。

一、shared_ptr

用于new创建的对象,而不适用于new[]创建的对象,
用于多个指针共享一个地址的情况。

#include<memory>

std::shared_ptr<int> int_ptr=new int;
//std::shared_ptr<int> int_ptr(new int);

二、unique_ptr

用于只存留一个指针指向最后地址的情况,
同时unique_ptr有指向new[]的版本。

其他

如ps是一个智能指针对象,则可以对它:

解除引用*ps
访问结构成员ps->index
将它赋给同类型常规指针

unique_ptr为右值时,可将其赋给shared_ptr
unique_ptr赋给另一个unique_ptr时,需要使用移动构造函数std::move()

猜你喜欢

转载自www.cnblogs.com/chendeqiang/p/11484290.html