六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 58|回复: 0

VC2010中C++的右值引用新特性

[复制链接]

升级  20%

76

主题

76

主题

76

主题

举人

Rank: 3Rank: 3

积分
260
 楼主| 发表于 2013-2-1 11:01:36 | 显示全部楼层 |阅读模式
// RightValue.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include <algorithm>#include <vector>#include <ctime>using namespace std;class CMyObj{protected:unsigned m_iBufferSize;char* m_pBuffer;public:CMyObj():m_iBufferSize(0),m_pBuffer(NULL){}CMyObj(unsigned int iBufSize):m_iBufferSize(iBufSize){m_pBuffer = new char[iBufSize];memset(m_pBuffer,0,m_iBufferSize);}CMyObj(const CMyObj& objSrc){m_iBufferSize = objSrc.m_iBufferSize;if(m_iBufferSize > 0){m_pBuffer = new char[m_iBufferSize];memcpy(m_pBuffer,objSrc.m_pBuffer,m_iBufferSize);}}~CMyObj(){if(m_pBuffer) delete m_pBuffer;m_pBuffer = NULL;}};class CMyObjWithMoveConstructor:public CMyObj{public:CMyObjWithMoveConstructor():CMyObj(){}CMyObjWithMoveConstructor(int iBufSize):CMyObj(iBufSize){}//copy constructorCMyObjWithMoveConstructor(const CMyObjWithMoveConstructor& myObj):CMyObj(myObj){}//move constructorCMyObjWithMoveConstructor(CMyObjWithMoveConstructor&& myObj){m_iBufferSize = myObj.m_iBufferSize;m_pBuffer = myObj.m_pBuffer;myObj.m_pBuffer = NULL;myObj.m_iBufferSize = 0;}};int _tmain(int argc, _TCHAR* argv[]){static int iBufSize = 1024*1024*2; //2Mstatic int iObjCnt = 100;clock_t t1,t2;double times;vector<CMyObj> vec;t1 = clock();//没有右值引用for( int i = 0; i < iObjCnt; i ++){ //加入100个元素vec.push_back( CMyObj(iBufSize));}t2 = clock();times = (double)(t2-t1)/CLOCKS_PER_SEC;cout<<"without move constructor:"<<times<<endl;vector<CMyObjWithMoveConstructor> vec2;t1 = clock();//有右值引用for( int j = 0; j < iObjCnt; j ++){ //加入100个元素vec2.push_back( CMyObjWithMoveConstructor(iBufSize));}t2 = clock();times = (double)(t2-t1)/CLOCKS_PER_SEC;cout<<"with move constructor:"<<times<<endl;return 0;}//最后结果://without move constructor:1.48//with move constructor:0.16//相差了9.25倍
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表