简体   繁体   English

为什么使用 std::move 并分配给 rvalue 不会窃取内部内容?

[英]why using std::move and assign to rvalue does not steal internal content?

As is known to all that c++ std::move would steal internal content if used with non-fundamental type.众所周知,如果与非基本类型一起使用,c++ std::move 会窃取内部内容。 I suddenly have a brainwave that what will happen to rvalue if move a lvalue to it.我突然想到如果将左值移动到右值会发生什么。 I initially thought it would still steal the content.我最初认为它仍然会窃取内容。 But nothing happened,a has its string still.但是什么也没发生,a 的字符串还在。 Does this caused by ignoring the move constructor?这是由于忽略了移动构造函数引起的吗? But I think a named rvalue is deemded by compiler to be lvalue, right?但我认为编译器认为命名的右值是左值,对吧?

int main()
{
    string a="4";
    string&& c = move(a);
    cout<<a<<endl;
}

It is because c is declared as a reference (rvalue reference) to a.这是因为c被声明为对 a 的引用(右值引用)。 It is not a different string.它不是一个不同的字符串。 In order to "still" (ie call the move constructor), c needs to be declared a string .为了“静止”(即调用移动构造函数),需要将c声明为string Then, string a is "moved" to string c:然后,字符串 a 被“移动”到字符串 c:

int main()
{
    string a="4";
    string c = move(a);
    cout<< "a :" <<a << ":" <<endl;
    
    cout << "c :" << c << ":"<< endl;
}

Output is: Output 是:

a ::                                                                                                                                           
c :4:

This code moves an rvalue to an lvalue though, which is the way it's supposed to work.这段代码将一个右值移动到一个左值,这是它应该工作的方式。 However, it sounds like you're trying to move an lvalue to an rvalue, but that is not what you're doing.但是,听起来您正在尝试将左值移动到右值,但这不是您正在做的事情。 c is an rvalue, but move(a) is also an rvalue. c是一个右值,但move(a)也是一个右值。 std::move() casts a to an rvalue reference. std::move()a强制转换为右值引用。 Think of a reference as something similar to a pointer, it is not a string .将引用视为类似于指针的东西,它不是string You can't move or copy a string to it.您不能将字符串移动或复制到其中。 It just refers to the string.它只是指字符串。 Anyway, I don't think that you can move lvalues to rvalues.无论如何,我认为您不能将左值移动到右值。 I can't think of any case.我想不出任何情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM