#include <stdio.h>
#include <tchar.h>
#include <vector>
#include <iostream>
using namespace std;
class ObjA
{
public:
ObjA():data(NULL)
{
cout<<_T("调用构造函数")<<endl;
}
ObjA(const char *_data)
{
int Len=strlen(_data);
data=new char[Len];
memcpy(data,_data,Len);
cout<<data<<endl;
cout<<_T("调用带参构造函数 memcpy")<<endl;
}
~ObjA()
{
if (data)
{
cout<<data<<endl;
delete[] data;
data=NULL;
cout<<"delete memory data"<<endl;
}
cout<<_T("调用析构函数.")<<endl;
}
//拷贝赋值
ObjA& operator=(const ObjA &b)
{
int Len=strlen(b.data);
data=new char[Len];
memcpy(data,b.data,Len);
cout<<_T("调用operator = 函数. memcpy")<<endl;
return *this;
}
ObjA(const ObjA &b)
{
cout<<_T("调用拷贝构造函数. memcpy")<<endl;
if (this!=&b)
{
int Len=strlen(b.data);
data=new char[Len];
memcpy(data,b.data,Len);
}
}
//Move拷贝构造函数
ObjA(ObjA &&b)
{
cout<<"Move拷贝构造函数"<<endl;
if (this!=&b)
{
data=b.data;
b.data=NULL;
}
}
//Move赋值拷贝
ObjA& operator=(ObjA &&b)
{
cout<<_T("Move operator = 函数.")<<endl;
if (this!=&b)
{
data=b.data;
b.data=NULL;
}
return *this;
}
char *data;
};
ObjA testRValue_ChangeStr(ObjA o)
{
delete[] o.data;
char *tmp="string after change";
int Len=strlen(tmp);
o.data=new char[Len];
memcpy(o.data,tmp,Len);
return o;
}
int _tmain(int argc, _TCHAR* argv[])
{
ObjA a("obj A");
ObjA b("obj B");
b=testRValue_ChangeStr(a);//b Move拷贝了testRVa...函数返回的临时对象的数据.
//test vector
vector<ObjA> *v=new vector<ObjA>;
//push_back每调用一次,就会调用Move拷贝构造函数
//把旧内存里的对象移至新分配的内存里去.
v->push_back(*new ObjA("C"));
v->push_back(*new ObjA("D"));
v->push_back(*new ObjA("E"));
//以上总共调用了三次memcpy函数,移动数据
return 0;
}
原文链接: https://www.cnblogs.com/ynwlgh/archive/2012/10/30/2746708.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/67539
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!