🔴 加不加 `&`,拷贝次数差几
(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)⚠️ 这一节的拷贝计数**只数标准强制的那几种**(传值给函数、push_back 一个左值),**不数返回值和临时对象**——那些各编译器会省略得不一样。所以这些数换台机器也不变。
#include <iostream>
#include <string>
#include <vector>
struct Item {
std::string name;
static int copies;
explicit Item(std::string n) : name(std::move(n)) {}
Item(const Item &o) : name(o.name) { copies++; }
Item &operator=(const Item &) = default;
};
int Item::copies = 0;
int main() {
std::vector<Item> v;
v.reserve(3);
v.push_back(Item("a")); /* 传的是临时对象,不记账 */
v.push_back(Item("bb"));
v.push_back(Item("ccc"));
int base = Item::copies; /* 从这里开始数 */
int n1 = 0;
for (Item x : v) n1 += static_cast<int>(x.name.size()); /* 每个都拷一份 */
int after_copy = Item::copies - base;
int n2 = 0;
for (const Item &x : v) n2 += static_cast<int>(x.name.size()); /* 一次都不拷 */
int after_ref = Item::copies - base - after_copy;
std::cout << n1 << "/" << n2 << "/" << after_copy << "/" << after_ref << "\n";
return 0;
}
全部评论