为什么我必须在右值引用上调用move? [英] Why do I have to call move on an rvalue reference?
问题描述
在下面的代码中,为什么第一次调用mkme = mvme_rv
不会分派给T& operator=(const T&&)
?
In the code below, why doesn't the first call mkme = mvme_rv
dispatch to T& operator=(const T&&)
?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using T = vector<int>;
int main()
{
T mvme(10, 1), mkme;
T&& mvme_rv = move(mvme); // rvalue ref?
mkme = mvme_rv; // calls T& operator=(const T&)?
cout << mvme.empty(); // 0
mkme = move(mvme_rv); // calls T& operator=(const T&&)?
cout << mvme.empty(); // 1
}
推荐答案
当skypjack正确注释时,通过对象名称访问对象始终会产生左值引用.
As skypjack correctly comments, accessing an object through its name always results in an lvalue reference.
这是一项安全功能,如果您认为它是正确的,那么您将意识到您对此感到高兴.
This is a safety feature and if you think it through you will realise that you are glad of it.
如您所知,std::move
只是将l值引用转换为r值引用.如果我们立即使用返回的r值引用(即未命名),则它仍然是r值引用.
As you know, std::move
simply casts an l-value reference to an r-value reference. If we use the returned r-value reference immediately (i.e. un-named) then it remains an r-value reference.
这意味着只能在代码中提到move(x)
的位置使用r值.从代码阅读器的角度来看,现在很容易看到x的状态变为未定义状态.
This means that the use of the r-value can only be at the point in the code where move(x)
is mentioned. From a code-reader's perspective, it's now easy to see where x's state became undefined.
如此:
1: auto x = make_x();
2: auto&& r = std::move(x);
3: // lots of other stuff
35: // ...
54: // ...
55: take_my_x(r);
不起作用.如果确实如此,则维护代码的人将很难看到(并记住)x(在第1行定义)通过第2行上的引用进入第55行的未定义状态.
does not work. If it did, someone maintaining the code would have a hard time seeing (and remembering) that x (defined on line 1) enters an undefined state on line 55 through a reference taken on line 2.
这很明确:
1: auto x = make_x();
2: //
3: // lots of other stuff
35: // ...
54: // ...
55: take_my_x(std::move(x));
这篇关于为什么我必须在右值引用上调用move?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!