取消引用右值引用会有什么作用吗?

问题描述 投票:0回答:1

假设我有这个代码:

std::unique_ptr<int> ptr = std::make_unique<int>(10);

int val = *std::move(ptr);

// Anything using ptr after

我知道 std::move 为我们提供了对 unique_ptr 的右值引用,并且我不认为取消引用会像移动赋值运算符那样从 ptr 中窃取资源,因此如果没有std::移动?

如果我希望在将 ptr 的值设置为 val 后释放分配给 ptr 的资源,这样可以实现吗?

c++ pointers
1个回答
1
投票

要了解

*std::move(ptr)
是否对唯一指针执行任何操作,您需要阅读
std::unique_ptr::operator*
的文档(例如此处:https://en.cppreference.com/w/cpp/memory/unique_ptr/operator* )发现它只有一个重载:

typename std::add_lvalue_reference<T>::type operator*() const
noexcept(noexcept(*std::declval<pointer>()));

这是一个

const
方法。它不能不修改唯一指针。

因此,一般来说

std::move
只是一个强制转换,在这里它没有任何效果。
*
取消引用唯一指针,并创建所包含的
int
的副本。唯一指针不会被
*std::move(ptr)
修改。

© www.soinside.com 2019 - 2024. All rights reserved.