前言
智能指针似乎越来越广泛的使用了。有必要好好记住。
shared_ptr
shared_ptr允许多个指针指向同一个对象,unique_ptr则独占所指的对象。
例子
#include <memory>
#include <thread>
class A
{
char * str;
public:
A(){
str = new char[20];
printf("构造\n");
}
~A()
{
printf("析构\n");
delete [] str;
}
};
std::shared_ptr<A> xixi;
void test()
{
std::shared_ptr<A> shared_a = std::make_shared<A>();
xixi = shared_a;
printf("%d\n", xixi.use_count());
}
int main()
{
test();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
上面这个例子中,xixi是全局智能指针,会在程序结束时才会释放自己所指向的对象,如果去掉了xixi=shared_a,则在main函数延迟之前就会看到析构。
unique_ptr
unique_ptr独占对象,只能在不同的unique_ptr中移动(std::move)。没有make_unique语句。只能在构造函数中传入对象的指针来构造unique_ptr。
unique_ptr使用场景 1、为动态申请的资源提供异常安全保证 我们先来看看下面这一段代码:
void Func()
{
int *p = new int(5);
// ...(可能会抛出异常)
delete p;
}
这是我们传统的写法:当我们动态申请内存后,有可能我们接下来的代码由于抛出异常或者提前退出(if语句)而没有执行delete操作。
解决的方法是使用unique_ptr来管理动态内存,只要unique_ptr指针创建成功,其析构函数都会被调用。确保动态资源被释放。
void Func()
{
unique_ptr<int> p(new int(5));
// ...(可能会抛出异常)
}
week_ptr
week_ptr也是一种强大的指针,名字起的比较弱。week_ptr不控制对象的生命周期,用于在不持有对象时使用。week_ptr可以在对象存在时提升为shared_ptr。