我正在研究C++中的完美转发机制,我对std::move()
有一些疑问。功能。这是一个可能的实现:
template<class T>
typename remove_reference<T>::type&&
std::move(T&& a) noexcept {
typedef typename remove_reference<T>::type&& RvalRef;
return static_cast<RvalRef>(a);
}
在 std::unique_ptr<>
上使用时, 此函数将资源的所有权从一个指针转移到另一个指针。
我发现这个函数的重点是从左值引用到右值引用到推导的 T
的转换。类型。
#include <iostream>
#include <memory>
using namespace std;
int main() {
unique_ptr<int> p1(new int(20));
unique_ptr<int> p2;
unique_ptr<int> &r = p1;
cout << "p1 = " << p1.get() << endl;
cout << "p2 = " << p2.get() << endl;
// These 2 instructions produce the same effect (then consider just one of them).
p2 = static_cast<unique_ptr<int>&&>(r);
//p2 = move(p1);
cout << "p1 = " << p1.get() << endl;
cout << "p2 = " << p2.get() << endl;
return 0;
}
输出:
p1 = 0x467b10
p2 = 0
p1 = 0
p2 = 0x467b10
我想知道当我从 L 引用转换为 R 引用时会发生什么 std::unique_ptr<int>
类型。
最佳答案
std::move
不移动,std::forward
不转发。
move
只是将一种引用转换为另一种引用。它接受一个引用,并返回对相同数据的右值引用。这在运行时什么都不做。移动的是使用此右值引用的代码。
该代码现在被告知“像对待临时未命名对象一样对待它”(不完全是,但接近)。最常见的使用者是“移动构造函数”或“移动赋值”,这是使用 unique_ptr
进行实际移动的内容。
至于forward
,它是一个条件移动,定义为与称为“完美转发”和/或“通用引用”的技术一起使用。它有时会移动,有时什么也不做。我之所以提到它,是因为我上面引用的那句精辟的话提到了它:这是另一个话题。
关于C++ 从左值引用转换为右值引用 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27468585/