四种智能指针:auto_ptr(C++11已经摒弃)、unique_ptr、shared_ptr 和 weak_ptr
1、unique_ptr(独占指针)
- 3种创建方式
using namespace std;
// 1.使用原始指针创建
A *p1 = new A("OK"); // A是一个类
unique_ptr<A> u_p1 ( p1 );
u_p1->print();
// 2.使用new的方式创建(推荐使用)
unique_ptr<A> u_p2 ( new A("OK") );
u_p2->print();
// 3.make_unique 创建(推荐使用)
unique_ptr<A> u_p3 = make_unique<A>("OK");
u_p3->print();
- 任何时刻,只能有一个指针管理内存,因此不支持拷贝和赋值操作,只能移动(move),这样所有权将会被转移
unique_ptr<A> u_p4 = move(u_p2);
u_p4->print();
u_p2->print(); // 程序崩溃,因为所有权转移了
- reset 方法 :可以解除原始内存的管理ÿ