有人能给我 xvalue 和 std::move() 行为的“非循环”定义/解释吗?
我查看了 cppreference 页面,上面写着“std::move() 产生一个 xvalue”。 (好的)
然后我查找“xvalue”的定义,它说的第一件事是它是一个函数调用或重载运算符表达式,例如“std:move”。 (???)
最佳答案
std::move()
将表达式从左值或右值转换为x值 .
左值是一个占用内存中某个位置的对象,而右值则暂时占用内存。
int main() {
int x = 3 + 4;
std::cout << x << std::endl;
}
在上面的示例中,x
是左值,3 + 4
是右值。现在看到 x
不是临时值,而 3 + 4
表达式是临时值。
现在考虑一下您这样做:int y = x;
。您的内存中有该 x
的两个拷贝,对吧?
检查下面的示例:
swap(int &a, int &b) {
int tmp = a; // Two copies of a; one of them is tmp
a = b; // Two copies of b; one of them is a
b = tmp; // Two copies of tmp; one of them is b
}
使用 std::move()
检查以下示例:
swap(int &a, int &b) {
int tmp = std::move(a); // tmp is an xvalue
a = std::move(b);
b = std::move(tmp);
}
你不能复制;你可以把它们移到某个地方。实际上,你传输它的内容一段时间。他们很快就会被摧毁。它们现在是 xvalue
:)
关于c++ - C++ 中的 std::move() 和 xvalue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507641/