Kodewick
開始學 →
複製和移動18 / 30

C++ 複製和移動

第 18 課,共 30 課 · 第 4 部分 · 類 · 約 20 分鐘

複製物件時呼叫複製建構函式,把內容複製一份;std::move 把資源直接轉交給新物件,呼叫移動建構函式,省掉複製。

int 賦給另一個變數是複製一份,物件也一樣:Playlist b = a; 以後,b 是一個新的歌單,裡面的歌也是複製過去的。改 b 不影響 a:

main.cpp
1#include <iostream>2#include <string>3#include <vector>4 5class Playlist {6public:7    void add(const std::string& song) {8        songs_.push_back(song);9    }10 11    int count() const {12        return songs_.size();13    }14 15private:16    std::vector<std::string> songs_;17};18 19int main() {20    Playlist a;21    a.add("第一首");22    a.add("第二首");23    Playlist b = a;24    b.add("第三首");25    std::cout << a.count() << " " << b.count() << '\n';26    return 0;27}
輸出
2 3

點單步,看畫面上 a 和 b 是兩個物件,各有自己的一排歌。這一課講複製是怎麼發生的、怎麼不讓複製,以及比複製更省事的移動。

b = a 複製出一個新歌單:a 和 b 各有自己的一排歌,往 b 裡加歌,a 不變
猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2#include <vector>3 4int main() {5    std::vector<int> a{1, 2};6    std::vector<int> b = a;7    b.push_back(3);8    a[0] = 9;9    std::cout << a.size() << b.size() << ' ' << b[0] << '\n';10    return 0;11}

複製建構函式

用一個已有的物件做出一個新物件時,呼叫的是複製建構函式。這一課開頭的例子沒寫,編譯器替你生成了一個:一個成員一個成員地複製。自己寫一個,讓它顯示一行,就能看見覆制在什麼時候發生:

main.cpp
1#include <iostream>2#include <string>3 4class Playlist {5public:6    Playlist(const std::string& name) : name_(name) {}7 8    Playlist(const Playlist& other) : name_(other.name_) {9        std::cout << "複製了 " << name_ << '\n';10    }11 12private:13    std::string name_;14};15 16void by_value(Playlist p) {17}18 19void by_ref(const Playlist& p) {20}21 22int main() {23    Playlist a{"跑步"};24    Playlist b = a;25    Playlist c{a};26    by_value(a);27    by_ref(a);28    return 0;29}
輸出
複製了 跑步
複製了 跑步
複製了 跑步

複製建構函式的引數是 const Playlist&:從 other 那裡抄,不改它。Playlist b = a;、Playlist c{a}; 都是複製;按值傳參也是複製(第 8 課說的「函式拿到的是一份複製」就是它做的)。by_ref 拿的是引用,沒有複製。

單選猜錯也沒關係

check 呼叫了 3 次,一共顯示幾個「複製」?

1#include <iostream>2 3class Ticket {4public:5    Ticket(int number) : number_(number) {}6 7    Ticket(const Ticket& other) : number_(other.number_) {8        std::cout << "複製 ";9    }10 11private:12    int number_;13};14 15void check(Ticket t) {16}17 18int main() {19    Ticket t{7};20    for (int i = 0; i < 3; i++) {21        check(t);22    }23    std::cout << '\n';24    return 0;25}
練習 1

複製出來的是副本

給 Document 寫一個複製建構函式:標題後面加上「(副本)」,正文照抄。程式要顯示下面兩行。

要顯示
週末計劃:去爬山
週末計劃(副本):去爬山
exercise1.cpp
1#include <iostream>2#include <string>3 4class Document {5public:6    Document(const std::string& title, const std::string& text) : title_(title), text_(text) {}7 8    void show() const {9        std::cout << title_ << ":" << text_ << '\n';10    }11 12private:13    std::string title_;14    std::string text_;15};16 17int main() {18    Document plan{"週末計劃", "去爬山"};19    Document copy = plan;20    plan.show();21    copy.show();22    return 0;23}
輸出
點「執行」或按 Ctrl+Enter

複製賦值

b = a; 和 Playlist b = a; 看起來很像,其實不一樣:前者的 b 早就有了,是把 a 的內容抄過來蓋掉舊的,呼叫的是複製賦值運算子 operator=:

main.cpp
1#include <iostream>2#include <string>3 4class Playlist {5public:6    Playlist(const std::string& name) : name_(name) {}7 8    Playlist(const Playlist& other) : name_(other.name_) {9        std::cout << "複製構造:" << name_ << '\n';10    }11 12    Playlist& operator=(const Playlist& other) {13        name_ = other.name_;14        std::cout << "複製賦值:" << name_ << '\n';15        return *this;16    }17 18private:19    std::string name_;20};21 22int main() {23    Playlist a{"跑步"};24    Playlist b{"睡前"};25    Playlist c = a;26    b = a;27    return 0;28}
輸出
複製構造:跑步
複製賦值:跑步

看等號左邊是不是正在宣告的新變數:Playlist c = a; 聲明瞭新的 c,是複製構造;b = a; 的 b 已經存在,是複製賦值。和上一課的 += 一樣,operator= 返回 *this 的引用。

複製構造Playlist c = a;c 是新做出來的c 正在宣告
複製賦值b = a;蓋掉 b 原來的內容b 早就有了
看等號左邊:是正在宣告的新變數,就是複製構造;是早就有的物件,就是複製賦值
單選

Playlist x{"x"}; Playlist y{"y"}; y = x; 最後一句呼叫的是哪個?

= delete:不許複製

有些東西複製了就亂了。一個銀行賬戶複製出一份,兩份都有 100 塊錢,到底算誰的?在複製建構函式和複製賦值後面寫 = delete,就把它們刪掉了,誰複製都是編譯錯誤:

main.cpp
1#include <iostream>2#include <string>3 4class Account {5public:6    Account(const std::string& owner, int balance) : owner_(owner), balance_(balance) {}7    Account(const Account&) = delete;8    Account& operator=(const Account&) = delete;9 10    int balance() const {11        return balance_;12    }13 14private:15    std::string owner_;16    int balance_;17};18 19int main() {20    Account mine{"小林", 100};21    Account copy = mine;22    std::cout << copy.balance() << '\n';23    return 0;24}
輸出
main.cpp: In function 'int main()':
main.cpp:21:20: error: use of deleted function 'Account::Account(const Account&)'
   21 |     Account copy = mine;
      |                    ^~~~

use of deleted function 'Account::Account(const Account&)':用了被刪掉的函式。不能複製的物件,傳給函式時就用引用(const Account& 或 Account&)。

單選

Account 的複製被 = delete 了。要把它傳給函式 show,引數該怎麼寫?

練習 2

修好它:賬戶不能複製

Account 不許複製,所以程式編譯不過。不要改 Account,只改 report,讓程式顯示 小林:100。

要顯示
小林:100
exercise2.cpp
1#include <iostream>2#include <string>3 4class Account {5public:6    Account(const std::string& owner, int balance) : owner_(owner), balance_(balance) {}7    Account(const Account&) = delete;8    Account& operator=(const Account&) = delete;9 10    void show() const {11        std::cout << owner_ << ":" << balance_ << '\n';12    }13 14private:15    std::string owner_;16    int balance_;17};18 19void report(Account acc) {20    acc.show();21}22 23int main() {24    Account mine{"小林", 100};25    report(mine);26    return 0;27}
輸出
點「執行」或按 Ctrl+Enter

移動:搬走,不復制

複製一個裝著幾千首歌的歌單,要把每首歌都抄一遍。可如果原來那個反正不要了,直接把裡面的東西搬過去就行,快得多。std::move(在 <utility> 裡)就是說「這個可以搬走」:

main.cpp
1#include <iostream>2#include <string>3#include <utility>4#include <vector>5 6int main() {7    std::string draft = "今天的日記";8    std::vector<std::string> diary;9    diary.push_back(draft);10    diary.push_back(std::move(draft));11    std::cout << diary.size() << '\n';12    std::cout << "[" << draft << "]\n";13    return 0;14}
輸出
2
[]

第一次 push_back(draft) 是複製,draft 還在;第二次 push_back(std::move(draft)),文字被搬進了 vector,draft 變空了。點單步,看 draft 在哪一步變空。

複製v.push_back(s)s 還在每個字都抄一遍
搬走v.push_back(std::move(s))s 被搬空直接轉交,快
複製是抄一份,原來的還在;std::move 是直接轉交,原來的空了

注意: 搬走以後的物件還能用來賦新值,也能正常死掉,但它裡面是什麼,標準只說「有效但不確定」(vector 的移動構造保證變空;string 在 g++ 上是空的)。所以搬走以後,別再讀它,要用就先給它一個新值。

單選

diary.push_back(std::move(draft)); 之後,對 draft 可以做什麼?

移動建構函式

自己的類也能寫移動建構函式。它的引數是 Playlist&&,兩個 & 表示「一個可以被搬走的東西」。做法是把每個成員也 std::move 過來:

main.cpp
1#include <iostream>2#include <string>3#include <utility>4#include <vector>5 6class Playlist {7public:8    Playlist(const std::string& name) : name_(name) {}9 10    Playlist(Playlist&& other) : name_(std::move(other.name_)), songs_(std::move(other.songs_)) {11        std::cout << "搬走了 " << name_ << '\n';12    }13 14    void add(const std::string& song) {15        songs_.push_back(song);16    }17 18    int count() const {19        return songs_.size();20    }21 22private:23    std::string name_;24    std::vector<std::string> songs_;25};26 27int main() {28    Playlist old_list{"跑步"};29    old_list.add("第一首");30    old_list.add("第二首");31    Playlist new_list = std::move(old_list);32    std::cout << new_list.count() << " " << old_list.count() << '\n';33    return 0;34}
輸出
搬走了 跑步
2 0

歌全都到了 new_list,old_list 剩 0 首。點單步,看 songs_ 那排格子從一個物件整個跑到另一個物件裡,一首歌都沒有複製。這裡讀 old_list.count() 只是為了看它空了:vector 搬走以後保證是空的。平時照「移動」那一關的注意,別去讀搬走的物件。

std::move 自己什麼都不搬,它只是給物件貼上「可以搬」的標籤;真正動手的是移動建構函式。要是你寫了複製建構函式、卻沒寫移動建構函式,貼了標籤也只會複製。(兩個都沒寫的話,編譯器會自己生成一個移動建構函式。)

填空點一個填進空格,再點空格可以拿回來

選一個符號填進空格,寫出 Box 的移動建構函式,讓程式顯示 move 2。

1#include <iostream>2#include <utility>3#include <vector>4 5class Box {6public:7    Box() {}8 9    Box(Box other) : items_(std::move(other.items_)) {10        std::cout << "move ";11    }12 13    void add(int x) {14        items_.push_back(x);15    }16 17    int count() const {18        return items_.size();19    }20 21private:22    std::vector<int> items_;23};24 25int main() {26    Box a;27    a.add(1);28    a.add(2);29    Box b = std::move(a);30    std::cout << b.count() << '\n';31    return 0;32}
練習 3

搬走,別複製

Inbox 只有複製建構函式,所以 std::move 也只能複製。給它加一個移動建構函式,顯示「搬走了」,把 messages_ 搬過去。程式要顯示下面兩行。(最後讀 old_box 只是為了看它空了:搬走的 vector 保證是空的。)

要顯示
搬走了
新:3 封,舊:0 封
exercise3.cpp
1#include <iostream>2#include <string>3#include <utility>4#include <vector>5 6class Inbox {7public:8    Inbox(const std::vector<std::string>& messages) : messages_(messages) {}9 10    Inbox(const Inbox& other) : messages_(other.messages_) {11        std::cout << "複製了\n";12    }13 14    int count() const {15        return messages_.size();16    }17 18private:19    std::vector<std::string> messages_;20};21 22int main() {23    Inbox old_box{{"你好", "開會", "賬單"}};24    Inbox new_box = std::move(old_box);25    std::cout << "新:" << new_box.count() << " 封,舊:" << old_box.count() << " 封\n";26    return 0;27}
輸出
點「執行」或按 Ctrl+Enter

三五法則

解構函式、複製構造、複製賦值、移動構造、移動賦值,這五個是一夥的:自己寫了其中一個,多半另外四個也要想一想。這叫「三五法則」(早先只有前三個,叫三法則)。

好訊息是,大多數類一個都不用寫。成員是 std::string、std::vector、int 這些時,編譯器生成的那五個已經會正確地複製、搬走、收拾,這有時被叫做「零法則」。這一課自己寫它們,只是為了讓你看見它們什麼時候被呼叫。

寫法呼叫的是
Playlist b = a; / Playlist b{a};複製構造
b = a;(b 已經有了)複製賦值
Playlist b = std::move(a);移動構造
b = std::move(a);(b 已經有了)移動賦值
按值傳參 f(a)複製構造
單選

一個類的成員只有 std::string、std::vector 和 int。五個特殊成員函式要自己寫幾個?

這一課學會了

  • 物件賦給新變數、按值傳參,都會複製出一個獨立的新物件,呼叫複製建構函式 T(const T& other)。
  • 已經存在的物件 b = a; 呼叫複製賦值 T& operator=(const T& other),最後返回 *this。
  • 在複製構造和複製賦值後面寫 = delete 就不許複製(use of deleted function);這樣的物件用引用傳。
  • std::move(x) 表示 x 可以搬走;移動建構函式 T(T&& other) 把成員搬過來,不復制。
  • 搬走以後的物件只能賦新值或者讓它死,別再讀它的值。
  • 五個特殊成員函式(析構、複製構造、複製賦值、移動構造、移動賦值)寫了一個就想想其餘的;成員都是 string、vector 這類時,一個都不用寫。
第 18 課學完了嗎?第 18 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 19 課 · 20 分鐘指標C++ 指標是存著位址的變數:& 取位址、* 順著位址找到變數、nullptr 表示不指著誰、通過指標改外面的變數、-> 訪問成員,以及指標和引用有什麼不同。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。