动机:减少非必要的拷贝
实现思路:
1、必须要语法让我们在调用端告诉编译器,这是个Rvalue std::move可以实现
2、必须有语法让我们在被调用端写出一个专门处理Rvalue的函数,参考std::string的实现
std::move 将实参强制转换成了右值,仅此而已
测试代码:
void test_move() {
for(int j = 13; j < 20; ++j) {
const int64_t times = 10;
std::string str = "tt";
for (int i = 0; i <= j; ++i) {
str += str;
}
cout << "test string size(kb):" << str.size()/1024 << endl;
cout << "move or copy times:" << times << endl;
std::vector<std::string> v_copy;
std::vector<std::string> v_move;
// 将使用 push_back(const T&), 即产生拷贝行为
auto begin = std::chrono::steady_clock::now();
for (int i = 0; i < times; ++i)
v_copy.push_back(str);
auto time = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - begin).count();
cout << "copy time(us):" << time << endl;
auto begin2 = std::chrono::steady_clock::now();
for (int i = 0; i < times; ++i)
v_move.push_back(std::move(str));
time = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - begin2).count();
cout << "move time(us):" << time << endl;
}
}
move和copy的时间比,时间单位us
数据大小(kb) | 操作1次 | 操作5次 |
32k | 1/24 | 4/171 |
64k | 1/42 | 3/235 |
128k | 1/70 | 4/474 |
256k | 1/164 | 10/916 |
512k | 1/297 | 4/1698 |
1024k | 1/593 | 3/3165 |
2028k | 1/1326 | 4/5630 |