为什么std :: move比复制慢?

时间:2015-11-13 06:35:10

标签: c++ c++11

考虑以下计划。为什么移动比复制慢?我认为当将函数作为rvalues返回本地时,移动语义会大大增加。你能告诉我为什么移动一个大矢量比复制它慢。返回shared_ptr的基准是作为基本情况提供的。

#include <iostream>
#include <vector>
#include <string>
#include <chrono>
using namespace std;

vector<int> getStringByCopy()
{
   vector<int> v;
   for (int x = 0; x< 15000000;x++)  v.push_back(x);
   return v;
}

vector<int>&& getStringByMove()
{
  vector<int> v;
  for (int x = 0; x< 15000000;x++)   v.push_back(x);
  return move(v);
}

shared_ptr<vector<int>> getStringByPointer()
{
   shared_ptr<vector<int>> v = make_shared<vector<int>>();
   for (int x = 0; x< 15000000;x++)   v->push_back(x);
   return v;
}
int main(int argc, const char * argv[]) {
   // insert code here...

   chrono::system_clock::time_point begin = chrono::system_clock::now();

   vector<int> v = getStringByCopy();

   chrono::system_clock::time_point end = chrono::system_clock::now();
   cout << v[0] << "copy took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;;

   begin = chrono::system_clock::now();

   vector<int>&& m = getStringByMove();

   end = chrono::system_clock::now();
   cout << m[0] << "move took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;;

   begin = chrono::system_clock::now();

   shared_ptr<vector<int>> sp = getStringByPointer();

   end = chrono::system_clock::now();
   cout << (*sp)[0] << "pointer took " << chrono::duration_cast<chrono::microseconds>(end - begin).count() << endl;

   return 0;
}

输出结果为:

0copy took 437043
0move took 462803
0pointer took 394549  

1 个答案:

答案 0 :(得分:1)

每个副本应该返回的方法已经按每次移动返回。如果返回方法中每个值在堆栈上分配的任何内容并返回它,那么您将获得自动移动。