std :: move()之后,unique_ptr会发生什么? [英] What happens to unique_ptr after std::move()?

查看:104
本文介绍了std :: move()之后,unique_ptr会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码是我想要做的:

Tony& Movie::addTony()
{
    Tony *newTony = new Tony;
    std::unique_ptr<Tony> tony(newTony);
    attachActor(std::move(tony));
    return *newTony;
}

我想知道我是否可以这样做:

I am wondering if I could do this instead:

Tony& Movie::addTony()
{
    std::unique_ptr<Tony> tony(new Tony);
    attachActor(std::move(tony));
    return *tony.get();
}

但是 * tony.get()是相同的指针还是null?我知道我可以验证,但是标准操作是什么?

But will *tony.get() be the same pointer or null? I know I could verify, but what is the standard thing for it to do?

推荐答案

否,您不能这样做.移动 unique_ptr 将其无效.如果不是,那么它将不是唯一的.我当然假设 attachActor 不会像这样愚蠢地做某事:

No, you cannot do that instead. Moving the unique_ptr nulls it. If it didn't, then it would not be unique. I am of course assuming that attachActor doesn't do something silly like this:

attachActor(std::unique_ptr<Tony>&&) {
    // take the unique_ptr by r-value reference,
    // and then don't move from it, leaving the
    // original intact
}

第20.8.1节第4段.

Section 20.8.1 paragraph 4.

另外,根据请求,u(unique_ptr对象)可以转移拥有另一个唯一指针u2的所有权.完成这样的转移,以下条件成立:
  -u2.p等于转移前的u.p,
   - u.p等于nullptr
  -如果转移前的u.d保持状态,则该状态已转移到u2.d.

Additionally, u (the unique_ptr object) can, upon request, transfer ownership to another unique pointer u2. Upon completion of such a transfer, the following postconditions hold:
   -- u2.p is equal to the pre-transfer u.p,
   -- u.p is equal to nullptr, and
   -- if the pre-transfer u.d maintained state, such state has been transferred to u2.d.

这篇关于std :: move()之后,unique_ptr会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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