unique_ptr管理的是一个指针,并且这个指针只能由一个unique_ptr进行管理。
这就使得,unique_ptr之间是不能进行赋值的。
比如以下代码:
void test() { unique_ptr p(new MyClass); unique_ptr p2; p2 = p; p->hello(); return;}
在编译的时候,就直接报错了。
![ecea360b7a131a882d87f439976d8314.png](https://img-blog.csdnimg.cn/img_convert/ecea360b7a131a882d87f439976d8314.png)
这个赋值操作是被删除的函数。
同样如果作为参数,也是不能用的。
![17605e47946d615dffe0e0bc7d9dd453.png](https://img-blog.csdnimg.cn/img_convert/17605e47946d615dffe0e0bc7d9dd453.png)
但是如果作为引用传递,却是没有问题的,毕竟引用不需要复制对象。
![e6afcd40639730c7146267b4aa26197c.png](https://img-blog.csdnimg.cn/img_convert/e6afcd40639730c7146267b4aa26197c.png)
接着我们看一下返回一个unique_ptr。