[关闭]
@zhengyuhong 2015-06-10T03:56:00.000000Z 字数 1508 阅读 1642

move forward

C++11 STL


move

  1. template <class T>
  2. typename remove_reference<T>::type&& move (T&& arg) noexcept;

  我对move的理解就是,它使得程序员在拷贝,赋值时更好利用一次性的局部变量。
Returns an rvalue reference to arg.
The function returns the same as:static_cast<remove_reference<decltype(arg)>::type&&>(arg)
example

  1. #include <utility> // std::move
  2. #include <iostream> // std::cout
  3. #include <vector> // std::vector
  4. #include <string> // std::string
  5. int main () {
  6. std::string foo = "foo-string";
  7. std::string bar = "bar-string";
  8. std::vector<std::string> myvector;
  9. myvector.push_back (foo); // copies
  10. myvector.push_back (std::move(bar)); // moves
  11. std::cout << "myvector contains:";
  12. for (std::string& x:myvector) std::cout << ' ' << x;
  13. std::cout << '\n';
  14. return 0;
  15. }

forward

  1. template <class T> T&& forward (typename remove_reference<T>::type& arg) noexcept;
  2. template <class T> T&& forward (typename remove_reference<T>::type&& arg) noexcept;

函数功能:当T为左值引用类型时,arg将被转换为T类型的左值,否则arg将被转换为T类型右值。如此定义std::forward是为了在使用右值引用参数的函数模板中解决参数的完美转发问题。完美转发是指保留参数的左右值属性,从而实现了函数模板参数的完美转发。如下图,在fn中,x已经是具名变量,变成了左值了,但是在fn被调用时,x是属于右值变量,而forward就是继续保持它的右值属性。
example

  1. #include <utility> // std::forward
  2. #include <iostream> // std::cout
  3. // function with lvalue and rvalue reference overloads:
  4. void overloaded (const int& x) {std::cout << "[lvalue]";}
  5. void overloaded (int&& x) {std::cout << "[rvalue]";}
  6. // function template taking rvalue reference to deduced type:
  7. template <class T> void fn (T&& x) {
  8. overloaded (x); // always an lvalue
  9. overloaded (std::forward<T>(x)); // rvalue if argument is rvalue
  10. }
  11. int main () {
  12. int a;
  13. std::cout << "calling fn with lvalue: ";
  14. fn (a);
  15. std::cout << '\n';
  16. std::cout << "calling fn with rvalue: ";
  17. fn (0);
  18. std::cout << '\n';
  19. return 0;
  20. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注