@zhengyuhong
2015-06-10T03:56:00.000000Z
字数 1508
阅读 1642
C++11 STL
template <class T>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
#include <utility> // std::move#include <iostream> // std::cout#include <vector> // std::vector#include <string> // std::stringint main () {std::string foo = "foo-string";std::string bar = "bar-string";std::vector<std::string> myvector;myvector.push_back (foo); // copiesmyvector.push_back (std::move(bar)); // movesstd::cout << "myvector contains:";for (std::string& x:myvector) std::cout << ' ' << x;std::cout << '\n';return 0;}
template <class T> T&& forward (typename remove_reference<T>::type& arg) noexcept;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
#include <utility> // std::forward#include <iostream> // std::cout// function with lvalue and rvalue reference overloads:void overloaded (const int& x) {std::cout << "[lvalue]";}void overloaded (int&& x) {std::cout << "[rvalue]";}// function template taking rvalue reference to deduced type:template <class T> void fn (T&& x) {overloaded (x); // always an lvalueoverloaded (std::forward<T>(x)); // rvalue if argument is rvalue}int main () {int a;std::cout << "calling fn with lvalue: ";fn (a);std::cout << '\n';std::cout << "calling fn with rvalue: ";fn (0);std::cout << '\n';return 0;}
