简体   繁体   English

这段代码有什么作用? (关于右值引用的问题)

[英]What does this code do? (A question about rvalue references)

So I was reading "The C++ Programming Language" and this code got shown.所以我正在阅读“C++ 编程语言”,并且显示了这段代码。 How does it exactly work?它究竟是如何工作的? I tried asking elsewhere, watching a video on references and another one on basic move semantics but I'm still insanely confused.我尝试在其他地方询问,观看有关参考的视频和另一个有关基本移动语义的视频,但我仍然非常困惑。

template<typename T>
void swap(T& a, T& b)
{
  T tmp {static_cast<T&&>(a)};
  a = static_cast<T&&>(b);
  b = static_cast<T&&>(tmp);
}

Casting to T&& means movable reference.转换为T&&意味着可移动的参考。 You could have the same effect via std::move() .您可以通过std::move()获得相同的效果。 Movable reference means the functions can have a different overload for this type.可移动引用意味着函数可以对该类型具有不同的重载。 The required guarantee is that, after processing, the object that we 'move from' will remain in a valid-but-unspecified state.所需的保证是,在处理之后,我们“移出”的 object 将保留在有效但未指定的 state 中。 Sometimes it's way more effective than copying.有时它比复制更有效。 Eg, for vectors, you might simply swap the buffers in a swap operation.例如,对于向量,您可以简单地在交换操作中交换缓冲区。 The underlying operation here is T::operator=(T&&) that gets called.这里的底层操作是被调用的T::operator=(T&&)

This is used in order to employ move semantics, if possible, with these objects.如果可能,这用于对这些对象使用移动语义。 If move semantics are not possible then this automatically devolves to plain, garden-variety, copy-based swapping.如果移动语义是不可能的,那么这会自动转移到普通的、普通的、基于副本的交换。 The capsule summary is as follows.胶囊总结如下。 If you look at plain, garden-variety swapping:如果你看普通的、普通的交换:

T tmp{a};

a=b;

b=t;

If these objects are "heavy" there's going to be a lot of copying going on.如果这些对象“很重”,就会进行大量复制。 When you say a=b in C++, you are making a complete duplicate of an object .当您在 C++ 中说a=b时,您正在完全复制 object If b is a vector with a million values, congratulations: you now have two vectors with a million values.如果b是具有一百万个值的向量,那么恭喜:您现在有两个具有一百万个值的向量。 And, as soon as you have them, one of them gets destroyed (in the process of swapping).而且,一旦你拥有它们,其中一个就会被销毁(在交换过程中)。 A lot of work, all for nothing.很多工作,一无所有。

Move semantics avoid this needless overhead in situations that boil down to moving stuff around, in the end.在最终归结为移动东西的情况下,移动语义避免了这种不必要的开销。 Instead of creating a copy of an object it is "moved" directly from point A to point B, of sorts.它不是创建 object 的副本,而是直接从 A 点“移动”到 B 点。

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

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