简体   繁体   English

关于 std::move 的一些事情

[英]Something about std::move


std::string str1 = "hello";
std::string &&str2 = std::move(str1);
std::string str3(str2);
std::cout << str1 << std::endl;

I think at line 3 that str3 will steal str1, because std::string(std::string &&str) (or sth. like that) will be invoked.我认为在第 3 行,str3 将窃取 str1,因为将调用 std::string(std::string &&str)(或类似的东西)。 But the result is:但结果是:

test_move()
hello
test_move()

I want to know why the content str1 is still there after line 3.我想知道为什么内容 str1 在第 3 行之后仍然存在。


std::string str1 = "hello";
std::string &&str2 = std::move(str1);
std::string str3(str2);
std::cout << str1 << std::endl;

std::string str4(std::move(str1));
std::cout << str1 << std::endl;

I try to move str1 directly to str4, and the result is:我尝试将str1直接移动到str4,结果是:

test_move()
hello 

test_move()

So I can't figure out the difference between the situation of str4 and str3.所以一直搞不清楚str4和str3的情况有什么区别。 In my eyes they are all the same, all takes a rvalue ref as parameter, but move semantics takes place only on str4.Why?在我看来,它们都是一样的,都以右值 ref 作为参数,但移动语义只发生在 str4 上。为什么?

std::move doesn't actually move anything. std::move实际上并没有移动任何东西。 It merely creates an rvalue reference.它只是创建一个右值引用。

But since you initialize a variable with this rvalue reference, the variable itself becomes an lvalue.但是因为你用这个右值引用初始化了一个变量,变量本身变成了一个左值。 Passing the actual rvalue to an rvalue-constructor (as done in the second example) the constructor does the "moving".将实际的右值传递给右值构造函数(如第二个示例中所做的那样),构造函数执行“移动”。

If we create a small example program:如果我们创建一个小示例程序:

#include <iostream>
#include <utility>

struct Foo
{
    Foo() = default;

    Foo(Foo const&)
    {
        std::cout << "l-value copy construction\n";
    }

    Foo(Foo&&)
    {
        std::cout << "r-value move construction\n";
    }
};

int main()
{
    {
        Foo a;
        Foo&& b = std::move(a);
        Foo c(b);
    }

    {
        Foo a;
        Foo b(std::move(a));
    }
}

If you build and run it then you will see that it will invoke the lvalue copy constructor for your first case.如果您构建并运行它,那么您将看到它将为您的第一个案例调用左值复制构造函数。

See it running eg here在这里看到它正在运行

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

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