简体   繁体   English

使用移动语义:右值引用作为方法参数

[英]Using move semantics: rvalue reference as a method parameter

I would like to doublecheck my understanding of move semantics.我想再次检查我对移动语义的理解。 Am I missing anything in my reasoning:我的推理中是否遗漏了什么:

#include <iostream>

using std::cout;

struct A
{
    A() {cout<<"Constructor\n";}
    ~A() {cout<<"Desctuctor\n";}
    A(const A&) {cout<<"Copy Constructor\n";}
    A(A&&) noexcept {cout<<"Move Constructor\n";}
    int x{1}; 
};

int f1(A a)
{
    cout<<"f1(A a)\n";
    return a.x;
}

int f2 (A&& a)
{
    cout<<"f2 (A&& a)\n";
    return a.x;
}

int main()
{
  A a1, a2;
  f1(std::move(a1));
  f2(std::move(a2));
}

Output: Output:

Constructor
Constructor
Move Constructor
f1(A a)
Desctuctor
f2 (A&& a)
Desctuctor
Desctuctor

From what I can see with f2() , I'm not creating any additional copies, even "light" move copies, which is cool.从我可以看到的f2() ,我没有创建任何额外的副本,甚至是“轻”移动副本,这很酷。 So my understanding now is that if I'm going to use move semantics, I better always write functions/methods signature to accept r-values as to avoid any unnecessary copies at all.所以我现在的理解是,如果我要使用移动语义,我最好总是编写函数/方法签名来接受 r 值,以避免任何不必要的复制。 Or there is something else I'm missing?还是我还缺少其他东西?

You're almost always best just taking inputs you're going to keep by value (except for odd types which have very high costs of moves).您几乎总是最好只接受您将按价值保留的输入(除了具有非常高移动成本的奇数类型)。

It maintains the same level of performance (in common scenarios) and keeps your code very simple to understand.它保持相同水平的性能(在常见场景中)并使您的代码非常易于理解。 It also makes it very clear that your code is keeping the value (because it's guaranteed to get moved out of), as an rvalue reference doesn't enforce that.它还非常清楚地表明您的代码保留了该值(因为它保证会被移出),因为右值引用不会强制执行这一点。

As you can see, the timings and generated code are identical for your examples when the print statements are removed: http://quick-bench.com/ADU4fzd0ISk0UrLboVhC-Pd7RmI如您所见,删除打印语句后,您的示例的时序和生成的代码是相同的: http://quick-bench.com/ADU4fzd0ISk0UrLboVhC-Pd7RmI

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

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