移動建構函式(c++常問問題十六)

來源:互聯網
上載者:User

標籤:

今天我們來講講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++常問問題十六)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.