🔴 一次拷贝、一次移动,摆在一起
(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)⚠️ 这一节的计数**只数标准强制的那几种**(传值/push_back 一个左值算拷贝,push_back 一个 std::move 过的算移动),**不数返回值和临时对象**——那些各编译器省略得不一样。
#include <iostream>
#include <string>
#include <vector>
struct Item {
std::string name;
static int copies, moves;
explicit Item(std::string n) : name(std::move(n)) {}
Item(const Item &o) : name(o.name) { copies++; }
Item(Item &&o) noexcept : name(std::move(o.name)) { moves++; }
Item &operator=(const Item &) = default;
Item &operator=(Item &&) = default;
};
int Item::copies = 0;
int Item::moves = 0;
int main() {
std::vector<Item> v;
v.reserve(4); /* 先占位,扩容搬运不掺进来 */
Item a("apple");
v.push_back(a); /* 左值:拷一份 */
int after_copy = Item::copies;
Item b("pear");
v.push_back(std::move(b)); /* 明说"搬走":移一份 */
int after_move = Item::moves;
std::cout << after_copy << "/" << after_move << "/"
<< Item::copies << "/" << v.size() << "\n";
return 0;
}
全部评论