std :: unique_ptr用法 [英] std::unique_ptr usage

查看:85
本文介绍了std :: unique_ptr用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::unique_ptr<int> p1(new int);
std::unique_ptr<int> p2(new int);
p2=p1;

在这里看来p1不再是唯一的",因为p2也引用了它.

It seems here that p1 is no longer "unique" since p2 refer to it also

这是合法的c ++吗?unique_ptr是否具有copy_semantics?如果否,并且仅具有移动语义,则在将p1分配给p2之后,是否将p1设置为NULL?

It is legal c++ ? Does unique_ptr have copy_semantics ? If no, and if it has only move semantics, is p1 set to NULL after assign it to p2 ?

好,所以正确的版本是

 p2=std::move(p1)

据此,在此分配之后,p1无效吗?和auto_ptr的区别在这里吗?明确指定所有权转移比隐式指定所有权更安全,因为我猜想auto_ptr就是这种情况

According to that, after this assign, p1 is not valid ? And the difference with auto_ptr is here? it is more safe to explictly specfiy transfer of ownership than implicitly as it is the case with auto_ptr I guess

推荐答案

std :: unique_ptr是不可分配和不可复制的.您需要使用std :: move();

std::unique_ptr is non-assignable and non-copyable. You need to use std::move();

如此

p1 = std::move(p2);

看看此处以获取更多信息.

这篇关于std :: unique_ptr用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆