1. 程式人生 > >C++11中std::move的使用

C++11中std::move的使用

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular,std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type.

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.) The move constructor is used instead of the copy constructor, if the object has type "rvalue-reference" (Type &&). std::move() is a cast that produces an rvalue-reference to an object, to enable moving from it.

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 incorrect state, avoiding to copy all data.

在C++11中,標準庫在<utility>中提供了一個有用的函式std::move,std::move並不能移動任何東西,它唯一的功能是將一個左值強制轉化為右值引用,繼而可以通過右值引用使用該值,以用於移動語義。從實現上講,std::move基本等同於一個型別轉換:static_cast<T&&>(lvalue);

std::move函式可以以非常簡單的方式將左值引用轉換為右值引用。

通過std::move,可以避免不必要的拷貝操作。

std::move是為效能而生。

std::move是將物件的狀態或者所有權從一個物件轉移到另一個物件,只是轉移,沒有記憶體的搬遷或者記憶體拷貝。

下面是從其他文章中copy的測試程式碼,詳細內容介紹可以參考對應的reference:

  1. #include "move.hpp"
  2. #include <iostream>
  3. #include <utility>
  4. #include <vector>
  5. #include <string>
  6. //////////////////////////////////////////////////////
  7. // reference: http://en.cppreference.com/w/cpp/utility/move
  8. int test_move1()  
  9. {  
  10.     std::string str = "Hello";  
  11.     std::vector<std::string> v;  
  12.     // uses the push_back(const T&) overload, which means we'll incur the cost of copying str
  13.     v.push_back(str);  
  14.     std::cout << "After copy, str is \"" << str << "\"\n";  
  15.     // uses the rvalue reference push_back(T&&) overload, which means no strings will be copied;
  16.     // instead, the contents of str will be moved into the vector.
  17.     // This is less expensive, but also means str might now be empty.
  18.     v.push_back(std::move(str));  
  19.     std::cout << "After move, str is \"" << str << "\"\n";  
  20.     std::cout << "The contents of the vector are \"" << v[0] << "\", \"" << v[1] << "\"\n";  
  21.     return 0;  
  22. }  
  23. ////////////////////////////////////////////////////
  24. // reference: http://www.ibm.com/developerworks/cn/aix/library/1307_lisl_c11/
  25. void ProcessValue(int& i)  
  26. {  
  27.     std::cout << "LValue processed: " << i << std::endl;  
  28. }  
  29. void ProcessValue(int&& i)  
  30. {  
  31.     std::cout << "RValue processed: " << i << std::endl;  
  32. }  
  33. int test_move2()  
  34. {  
  35.     int a = 0;  
  36.     ProcessValue(a);  
  37.     // std::move函式可以以非常簡單的方式將左值引用轉換為右值引用
  38.     ProcessValue(std::move(a));  
  39.     return 0;  
  40. }  
  41. /////////////////////////////////////////////////////////
  42. // reference: http://www.cplusplus.com/reference/utility/move/
  43. int test_move3()  
  44. {  
  45.     std::string foo = "foo-string";  
  46.     std::string bar = "bar-string";  
  47.     std::vector<std::string> myvector;  
  48.     // The first call to myvector.push_back copies the value of foo into
  49.     // the vector (foo keeps the value it had before the call).
  50.     // The second call moves the value of bar into the vector.
  51.     // This transfers its content into the vector(while bar loses its value,
  52.     // and now is in a valid but unspecified state)
  53.     myvector.push_back(foo);                    // copies
  54.     myvector.push_back(std::move(bar));         // moves
  55.     std::cout << "myvector contains:";  
  56.     for (std::string& x : myvector)  
  57.         std::cout << ' ' << x;  
  58.     std::cout << '\n';  
  59.     return 0;  
  60. }  

相關推薦

C++11std move的使用

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

C++11std::move的使用

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another

C++11std::movestd::forward、左右值引用、移動建構函式的測試

關於C++11新特性之std::move、std::forward、左右值引用網上資料已經很多了,我主要針對測試效能做一個測試,梳理一下這些邏輯,首先,左值比較熟悉,右值就是臨時變數,意味著使用一次就不會再被使用了。針對這兩種值引入了左值引用和右值引用,以及引用摺疊的概念。 1.右值引用的舉例測試 #in

C++11std condition variable的使用

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

C++11std::tuple的使用

std::tuple是類似pair的模板。每個pair的成員型別都不相同,但每個pair都恰好有兩個成員。不同std::tuple型別的成員型別也不相同,但一個std::tuple可以有任意數量的成員。每個確定的std::tuple型別的成員數目是固定的,但一個std::tu

C++11std condition variable的使用

                <condition_variable>是C++標準程式庫中的一個頭檔案,定義了C++11標準中的一些用於併發程式設計時表示條件變數的類與方法等。條件變數是併發程式設計中的一種控制結構。多個執行緒訪問一個共享資源(或稱臨界區)時,不但需要用互斥鎖實現獨享訪問以避免併

概率論中高斯分佈(正態分佈)介紹及C++11std::normal_distribution的使用

高斯分佈:最常用的分佈是正態分佈(normal distribution),也稱為高斯分佈(Gaussian distribution):正態分佈N(x;μ,σ2)呈現經典的”鐘形曲線”的形狀,其中中心峰的x座標由μ給出,峰的寬度受σ控制。正態分佈由兩個引數控制,μ∈R和σ∈

概率論伯努利分佈(bernoulli distribution)介紹及C++11std::bernoulli_distribution的使用

Bernoulli分佈(Bernoulli distribution):是單個二值隨機變數的分佈。它由單個引數ø∈[0,1],ø給出了隨機變數等於1的概率。它具有如下的一些性質:P(x=1)= øP(x=0)=1-øP(x=x)= øx(1-ø)1-xEx[x]= øVarx

c++11 move 與 forward

一. move 關於 lvaue 和 rvalue,在 c++11 以前存在一個有趣的現象:T&  指向 lvalue (左傳引用), const T& 既可以指向 lvalue 也可以指向 rvalue。但卻沒有一種引用型別,可以限制為只指向 rvalue。這乍看起來

概率論指數分佈介紹及C++11std::exponential_distribution的使用

指數分佈:在深度學習中,我們經常會需要一個在x=0點處取得邊界點(sharp point)的分佈。為了實現這一目的,我們可以使用指數分佈(exponential distribution):p(x;λ)= λlx≥0exp(-λx)指數分佈使用指示函式(indicator f

C++11 std::function和std::bind的用法

關於std::function 的用法: 其實就可以理解成函式指標 1. 儲存自由函式 void printA(int a) { cout<<a<<endl; } std::function<void(int a)

執行緒與互斥鎖(C++11std::thread和std::mutex的用法)

執行緒 0 首先是曾經在MultiCMOS專案中用到的: #include <thread> //包含標頭檔案 class IDataProcessUnit { protected:

C++11的技術剖析( std bind原理簡單圖解)

簡化 靜態成員函數 div 語法 con mar clear 函數 多余 此文為轉載,好像原出處的原文已經無法打開了。 本文解釋了bind 是如何工作的。為了清晰,我對圖中的語法作了一些簡化(例如,省略函數調用操作符的參數類型),並且簡化了 bind 的實現. bin

c++ 11emplace_back替代push_back的相關知識點,含右值引用,move用法等

C++11引入了右值引用,轉移建構函式,push_back()右值時就會呼叫建構函式和轉移建構函式(原來是呼叫拷貝構造,會為臨時變數申請堆空間,影響程式效率,C++11以後為右值引用呼叫轉移建構函式,不會為臨時變數申請堆空間,而是直接賦值,提高程式效率)。 使用mplace_back替代push_back()

C++11std::call_once

        某些場景下,我們需要程式碼只被執行一次,比如單例類的初始化,考慮到多執行緒安全,需要進行加鎖控制。C++11中提供的call_once可以很好的滿足這種需求,使用又非常簡單。 標頭檔案#include<mutex>         templat

c++11 的右值引用、 move 、 forward

再次來寫左值右值相關的東西我的內心是十分惴惴不安的,一來這些相關的概念十分不好理解,二來網上相關的文章實在太多了,多少人一看這類題目便大搖其頭,三來也怕說不清反而誤導了別人,反覆糾纏這些似乎無關大雅的語言細節實在也有成為 language lawyer 之嫌。但我還是決定再總結一次,因為這是我一直以來學習新

C++11智能指針的原理、使用、實現

his animal something include expire another .cn 表現 oid 目錄 理解智能指針的原理 智能指針的使用 智能指針的設計和實現 1.智能指針的作用 C++程序設計中使用堆內存是非

C++11多線程庫

標準 value 生命周期 通過 死鎖 strong () 四種 ... 一、linux 線程同步 線程是在操作系統層面支持的,所以多線程的學習建議還是先找一本linux系統編程類的書,了解linux提供多線程的API。完全完全使用系統調用編寫多線程程序是痛苦,現

C++11對容器的各種循環遍歷的效率比較

ets normal pre unsigned int qdebug tex contain string 1 #include "CycleTimeTst.h" 2 #include <string> 3 #include <vector&

C++11lock_guard和unique_lock的區別

target san color member uri display each for clas c++11中有一個區域鎖lock_guard,還有第二個區域鎖unique_lock。 區域鎖lock_guard使用起來比較簡單,除了構造函數外沒有其他member fu