標籤:
今天我們來講講c++11中引入了兩個新東西
1.move constructor(移動建構函式)
2.move assignment(移動賦值)
Rule of three現在變成了Rule of five(多了上面說的兩個東東)
class rule_of_five{ char* cstring; // raw pointer used as a handle to a dynamically-allocated memory block public: rule_of_five(const char* arg) : cstring(new char[std::strlen(arg)+1]) // allocate { std::strcpy(cstring, arg); // populate } ~rule_of_five() { delete[] cstring; // deallocate } rule_of_five(const rule_of_five& other) // copy constructor { cstring = new char[std::strlen(other.cstring) + 1]; std::strcpy(cstring, other.cstring); } rule_of_five(rule_of_five&& other) : cstring(other.cstring) // move constructor { other.cstring = nullptr; } rule_of_five& operator=(const rule_of_five& other) // copy assignment { char* tmp_cstring = new char[std::strlen(other.cstring) + 1]; std::strcpy(tmp_cstring, other.cstring); delete[] cstring; cstring = tmp_cstring; return *this; } rule_of_five& operator=(rule_of_five&& other) // move assignment { delete[] cstring; cstring = other.cstring; other.cstring = nullptr; return *this; }
那麼新加入的移動賦值以及移動拷貝要怎麼使用呢,直接看代碼
#include <iostream>#include <utility>#include <vector>#include <string>int main(){ std::string str = "Hello"; std::vector<std::string> v; // uses the push_back(const T&) overload, which means // we‘ll incur the cost of copying str v.push_back(str); std::cout << "After copy, str is \"" << str << "\"\n"; // uses the rvalue reference push_back(T&&) overload, // which means no strings will copied; instead, the contents // of str will be moved into the vector. This is less // expensive, but also means str might now be empty. v.push_back(std::move(str)); std::cout << "After move, str is \"" << str << "\"\n"; std::cout << "The contents of the vector are \"" << v[0] << "\", \"" << v[1] << "\"\n";}
Output:
After copy, str is "Hello"After move, str is ""The contents of the vector are "Hello", "Hello"
看完大概明白一點兒了,加上move之後,str對象裡面的內容被"移動"到新的對象中並插入到數組之中了,同時str被清空了。這樣一來省去了對象拷貝的過程。所以說在str對象不再使用的情況下,這種做法的效率更高一些!
移動建構函式(c++常問問題十六)