什么是 std::move(),什么时候应该使用它?

2022-01-30 00:00:00 c++ c++11 move-semantics c++-faq stdmove
  1. 这是什么?
  2. 它有什么作用?
  3. 什么时候使用?

好的链接表示赞赏.

推荐答案

维基百科页面关于 C++11 R 值引用和移动构造函数

  1. 在 C++11 中,除了复制构造函数,对象还可以有移动构造函数.
    (除了复制赋值运算符之外,它们还有移动赋值运算符.)
  2. 如果对象具有右值引用"类型(Type &&),则使用移动构造函数而不是复制构造函数.
  3. std::move() 是一种类型转换,它产生一个对对象的右值引用,以便从它移动.
  1. In C++11, in addition to copy constructors, objects can have move constructors.
    (And in addition to copy assignment operators, they have move assignment operators.)
  2. The move constructor is used instead of the copy constructor, if the object has type "rvalue-reference" (Type &&).
  3. std::move() is a cast that produces an rvalue-reference to an object, to enable moving from it.

这是一种避免复制的新 C++ 方法.例如,使用移动构造函数,std::vector 可以将其指向数据的内部指针复制到新对象,使移动对象处于已移动状态,因此不会复制所有数据.这将是 C++ 有效的.

It's a new C++ way to avoid copies. For example, using a move constructor, a std::vector could just copy its internal pointer to data to the new object, leaving the moved object in an moved from state, therefore not copying all the data. This would be C++-valid.

尝试在谷歌上搜索移动语义、右值、完美转发.

Try googling for move semantics, rvalue, perfect forwarding.

相关文章