移动构造、移动赋值函数

#include  "stdafx.h"
#include  
#include 
using namespace std;
 
#define  STR_NULL( str)    ( str!=NULL ?  str : "NULL" )

/*

std::move(t) 负责将表达式 t 转换为右值,使用这一转换意味着你不再关心 t 的内容,
它可以通过被移动(窃取)来解决移动语意问题。

 

*/




class String {
 
public:

String(const char* str = NULL);                //构造函数 
String(const String &other);                 //拷贝构造函数 
String& operator=(const String& other);  //赋值函数
virtual  ~String(void);  //析构函数




//C++ 11的新函数 
String(  String &&other);  //移动构造函数
String& operator=( String&& other);  //移动赋值函数


 
private:
char *m_data; // 用于保存字符串
};


inline String::String(const char* str)
{
if (str==NULL)
{
m_data = NULL;      //声明为inline函数,则该函数在程序中被执行时是语句直接替换,而不是被调用
}
else
{
m_data = new char[strlen(str) + 1];
strcpy_s(m_data, strlen(str) + 1,  str);
}


cout << "Construct   "<< STR_NULL(m_data) < }


 
inline String::String(const String &other)
{
if (other.m_data == NULL)
{
m_data = NULL;//在类的成员函数内可以访问同种对象的私有成员(同种类则是友元关系)
}
else
{
m_data = new char[strlen(other.m_data) + 1];
strcpy_s(m_data, strlen(other.m_data) + 1, other.m_data);
}


cout << "Copy construct   " << STR_NULL( m_data )<< endl;
}


inline String& String::operator=(const String& other)
{
if (this != &other)
{
delete[] m_data;
if (other.m_data==NULL)
{
m_data = NULL;
}
else
{
m_data = new char[strlen(other.m_data) + 1];
strcpy_s(m_data, strlen(other.m_data) + 1, other.m_data);
}
}


cout << "Operator=" << STR_NULL(m_data) << endl;


return *this;
}
 
String::~String(void)
{


cout << "Deconstruct    " << STR_NULL( m_data )<< endl;


if(m_data !=NULL)

  delete[] m_data; // 或delete m_data;
  m_data = NULL;

}


 
//移动构造函数
inline String::String(String &&other)  
{
m_data = move(other.m_data);//变成右值


    other.m_data = NULL;//此处置空避免被析构


cout << "Move construct   " << STR_NULL(m_data) << endl;
}


//移动赋值函数
inline String&  String::operator=(String&& other) 
{
m_data = move(other.m_data);//变成右值


other.m_data = NULL;//此处置空避免被析构


cout << "Move operator=   " << STR_NULL(m_data) << endl;


return *this;
}




String  test()
{
String  s( "aaa");
return s;
}


 


int main()
{
 
  String s1(  String ("aaa")  ); //构造函数




   String s2(  move(   String("bbb")  ) ); //移动构造函数


 
   String  s3= String("ccc"); //构造函数 


String  s4 = s3 ; //拷贝构造


    String  s5 = move (s3 ); //移动构造


s1 = s2; //赋值函数


s1 = move ( s2 ); //移动赋值函数


    s1 = String ("ddd"); //移动赋值函数
 
}




/*
打印:


Construct   aaa
Construct   bbb
Move construct   bbb
Deconstruct    NULL
Construct   ccc
Copy construct   ccc
Move construct   ccc
Operator=bbb
Move operator=   bbb
Construct   ddd
Move operator=   ddd
Deconstruct    NULL
Deconstruct    ccc
Deconstruct    ccc
Deconstruct    NULL
Deconstruct    NULL
Deconstruct    ddd




*/

你可能感兴趣的:(C++11)