分配 make_unique 是否需要 std::move() 给空的 unique_ptr?

问题描述 投票:0回答:3
#include <memory>
using namespace std;

int main()
{
    unique_ptr<int> a;

    // Do something....

    // Case 1
    a = make_unique<int>(5);

    // Case 2
    a = std::move(make_unique<int>(5));

    return 0;
}

我真正想问的是:

std::move 是否需要将临时的 unique_ptr 分配给空的 unique_ptr?两种情况都可以编译成功,但是不知道有什么区别吗

c++ unique-ptr move-semantics stdmove
3个回答
9
投票

事实并非如此,因为在这两种情况下,表达式都可能绑定到右值引用。

在第一个中,

std::make_unique
已经返回纯右值。

在第二个中,

std::move
强制转换为右值引用,这是多余的。

目标对象是否为空也并不重要。调用赋值的行为并不取决于它收到的引用是如何绑定的。结果是相同的,目标中先前的(可能不存在的)资源将被从源中“窃取”的资源替换。


4
投票

通过

std::make_unique
std::move
指针赋值时,不需要使用 std::unique_ptr。这适用于初始化:

std::unique_ptr<int> a = std::make_unique<int>(5);

和作业:

std::unique_ptr<int> a;
a = std::make_unique<int>(5);

实现已经为您完成转发:

return std::unique_ptr<T>(new T(std::forward<Args>(args)...));

3
投票

make_unique
是否需要将
std::move()
分配给
unique_ptr

没必要空着,做:

a = make_unique<int>(5);

相当于:

a.reset(make_unique<int>(5));

也就是说,

a
拥有的对象(如果有)被
make_unique
创建的新对象替换(释放后)。

是否需要

std::move
将临时
unique_ptr
分配给空
unique_ptr

make_unique
返回什么:

a = make_unique<int>(5);

已经是一个右值。因此,您不需要需要使用

std::move()
,如下面的代码所示:

a = std::move(make_unique<int>(5));
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.