本文介绍了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.

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

07-16 19:19
查看更多