C++ 複製和移動
複製物件時呼叫複製建構函式,把內容複製一份;std::move 把資源直接轉交給新物件,呼叫移動建構函式,省掉複製。
int 賦給另一個變數是複製一份,物件也一樣:Playlist b = a; 以後,b 是一個新的歌單,裡面的歌也是複製過去的。改 b 不影響 a:
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 是兩個物件,各有自己的一排歌。這一課講複製是怎麼發生的、怎麼不讓複製,以及比複製更省事的移動。
這段程式顯示什麼?
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}
b = a 複製了一份:b 有自己的元素。往 b 裡加 3、改 a[0],都只動一邊。a 有 2 個,b 有 3 個,b[0] 還是 1。複製建構函式
用一個已有的物件做出一個新物件時,呼叫的是複製建構函式。這一課開頭的例子沒寫,編譯器替你生成了一個:一個成員一個成員地複製。自己寫一個,讓它顯示一行,就能看見覆制在什麼時候發生:
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}
check(Ticket t) 按值傳參,每呼叫一次就複製一次。引數寫成 const Ticket& t 就一個都沒有了。複製出來的是副本
✓給 Document 寫一個複製建構函式:標題後面加上「(副本)」,正文照抄。程式要顯示下面兩行。
週末計劃:去爬山 週末計劃(副本):去爬山
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}
複製賦值
b = a; 和 Playlist b = a; 看起來很像,其實不一樣:前者的 b 早就有了,是把 a 的內容抄過來蓋掉舊的,呼叫的是複製賦值運算子 operator=:
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; 最後一句呼叫的是哪個?
y 在前面已經宣告過了,y = x; 是把 x 的內容抄過來蓋掉 y 原來的,所以是複製賦值。= delete:不許複製
有些東西複製了就亂了。一個銀行賬戶複製出一份,兩份都有 100 塊錢,到底算誰的?在複製建構函式和複製賦值後面寫 = delete,就把它們刪掉了,誰複製都是編譯錯誤:
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,引數該怎麼寫?
const Account&(要改它就用 Account&)傳。修好它:賬戶不能複製
✓Account 不許複製,所以程式編譯不過。不要改 Account,只改 report,讓程式顯示 小林:100。
小林:100
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}
移動:搬走,不復制
複製一個裝著幾千首歌的歌單,要把每首歌都抄一遍。可如果原來那個反正不要了,直接把裡面的東西搬過去就行,快得多。std::move(在 <utility> 裡)就是說「這個可以搬走」:
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 被搬空直接轉交,快注意: 搬走以後的物件還能用來賦新值,也能正常死掉,但它裡面是什麼,標準只說「有效但不確定」(vector 的移動構造保證變空;string 在 g++ 上是空的)。所以搬走以後,別再讀它,要用就先給它一個新值。
diary.push_back(std::move(draft)); 之後,對 draft 可以做什麼?
移動建構函式
自己的類也能寫移動建構函式。它的引數是 Playlist&&,兩個 & 表示「一個可以被搬走的東西」。做法是把每個成員也 std::move 過來:
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}
Box&&:兩個 & 表示「一個可以被搬走的東西」。std::move(a) 正好給出這樣的東西,於是呼叫它,把 items_ 搬過來。搬走,別複製
✓Inbox 只有複製建構函式,所以 std::move 也只能複製。給它加一個移動建構函式,顯示「搬走了」,把 messages_ 搬過去。程式要顯示下面兩行。(最後讀 old_box 只是為了看它空了:搬走的 vector 保證是空的。)
搬走了 新:3 封,舊:0 封
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}
三五法則
解構函式、複製構造、複製賦值、移動構造、移動賦值,這五個是一夥的:自己寫了其中一個,多半另外四個也要想一想。這叫「三五法則」(早先只有前三個,叫三法則)。
好訊息是,大多數類一個都不用寫。成員是 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這類時,一個都不用寫。