- unique_ ptr (唯一)是- -种定义在中的智能指针(smart pointer)。
- unique_ ptr 对象不能进行复制操作只能进行移动操作。
- unique是独特的、唯- -的意思, 故名思议,unique_ ptr 可以“独占"地拥有它所指向的对象。
unique_ ptr 和shared _ptr 类型指针有很大的不同:
-
shared_ ptr 允许多个指针指向同一对象
-
而unique_ptr 在某一时刻只能有一个指针指向该对象(两个unique_ _ptr 不能指向同一个对象)。
-
unique_ ptr对象中保存指向某个对象的指针,当它本身被删除或者离开其作用域时会自动释放其指向对象所占用的资源。
1、如何创建unique_ptr
- unique_ ptr 不像shared_ ptr 一样拥有标准库函数make_ shared 来创建一个shared_ _ptr 实例。
- 要想创建一个unique_ptr, 我们需要将一个new操作符返回的指针传递给unique_ptr的构造函数。
int main()
{
unique_ptr<int> pInt(new int(5));
cout<<*pInt;
}
2、无法进行复制构造和赋值操作
- unique_ptr 没有copy 构造函数,不支持普通的拷贝和赋值操作。
int main()
{
unique_ptr<int> pInt(new int(5));
unique_ptr<int> pInt2(pInt);//error
unique_ptr<int> pInt3;
pInt3 = pInt;//error
}
3、可以进行移动构造和移动赋值操作
- unique_ ptr虽然没有支持普通的拷贝和赋值操作,但却提供了一种移动机制来将指针的所有权从一 个unique_ptr转移给另一个unique_ ptr。
- 如果需要转移所有权,可以使用std::move()函数。
int main()
{
unique_ptr<int> pInt(new int(5));
unique_ptr<int> pInt2 = std::move(pInt);//转移所有权
cout<<*pInt<<endl;//error,pInt此时为空
cout<<*pInt2<<endl;
}
4、可以返回unique_ptr
- unique_ ptr不支持拷贝操作,但却有一个例外: 可以从函数中返回一个unique_ ptr.
unique_ptr<int> clone(int a)
{
unique_ptr<int> pInt(new int(a));
return Pint;//返回unique_ptr
}
int main()
{
int x = 5;
unique_ptr<int> reta = clone(x);
unique_ptr<int> retb;
retb = clone(x);
cout<<*reta<<endl;
cout<<*retb<<endl;
return 0;
}
unique_ptr使用场景
- 为动态申请的资源提供异常安全保证。
- 返回函数内动态申请资源的所有权。
- 在容器中保存指针。
- 管理动态数组。
图论