🔴 把拷贝次数数出来
(本条路线统一用 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;
void take_value(Item x) { (void)x; } /* 传值:标准强制拷一次 */
void take_ref(const Item &x) { (void)x; } /* 传 const& :一次都不拷 */
int main() {
Item a("apple");
int c0 = Item::copies;
take_value(a);
int c1 = Item::copies;
take_ref(a);
int c2 = Item::copies;
std::vector<Item> v;
v.reserve(4); /* 先占好位置,扩容搬运不掺进来 */
v.push_back(a); /* push_back(左值):拷一次 */
int c3 = Item::copies;
std::cout << c0 << "/" << c1 << "/" << c2 << "/" << c3 << "\n";
return 0;
}
全部评论