编程语言
首页 > 编程语言> > C++11:移动构造函数的测试

C++11:移动构造函数的测试

作者:互联网

C++11:移动构造函数的测试

 代码如下:

#include <iostream>
#include <stddef.h>
#include <Windows.h>

using namespace std;

class CTest
{
private:
  std::size_t size;
  char* buffer;

public:
  CTest(std::size_t size) : size(size), buffer(nullptr)
  {
    buffer = new char[size];
  }

  ~CTest()
  {
    delete[] buffer;
  }

  CTest(const CTest& other) : size(other.size), buffer(nullptr)
  {
    buffer = new char[size];
  }

  CTest(CTest&& other) : size(other.size), buffer(other.buffer)
  {
    other.buffer = nullptr;
  }
};

template <typename Func>
__int64 Benchmark(Func f, size_t count)
{
//   LARGE_INTEGER m_liPerfFreq={0};
//   //获取每秒多少CPU Performance Tick
//   QueryPerformanceFrequency(&m_liPerfFreq); 
  LARGE_INTEGER li = {};
  QueryPerformanceCounter(&li);
  __int64 start = li.QuadPart;

  f(count);

  QueryPerformanceCounter(&li);
  return (li.QuadPart - start);//* 1000 / m_liPerfFreq.QuadPart;
}

void Alloc_Ref(size_t count)
{
  CTest t(1024);
  for(size_t i = 0; i < count; ++i)
    CTest c(t);
}

void Alloc_Move(size_t count)
{
  CTest t(1024);
  for(size_t i = 0; i < count; ++i)
    CTest c(std::move(t));
    //CTest c(CTest(1024));

}

int _tmain(int argc, _TCHAR* argv[])
{
  for(int i= 0; i<10 ;++i)
  {
    cout << "Move: "<< Benchmark(Alloc_Move, 1000000) << " ms." << endl;
    cout << "Ref:  " << Benchmark(Alloc_Ref, 1000000) << " ms." << endl;    
  }

  system("pause");
    return 0;
}

程序运行结果如下:

结论:可见移动构造函数是拷贝构造函数的1-3倍。

参考链接:

VS 2010, Move constructor only reached after move() and slower than copy constructor?

标签:11,count,buffer,C++,li,other,构造函数,CTest,size
来源: https://www.cnblogs.com/2018shawn/p/10967077.html