C++:一段代碼,瞭解拷貝構造函數、move構造函數、拷貝賦值函數、move賦值函數、右值引用

本文純粹是個整理。html

如下代碼和圖片來自C++ 11右值引用函數

class CMyString
{
public:
    // 構造函數
 CMyString(const char *pszSrc = NULL)
 {
  cout << "CMyString(const char *pszSrc = NULL)" << endl;
  if (pszSrc == NULL)
  {
   m_pData = new char[1];
   *m_pData = '\0';
  }
  else
  {
   m_pData = new char[strlen(pszSrc)+1];
   strcpy(m_pData, pszSrc);
  }
 }

    // 拷貝構造函數
 CMyString(const CMyString &s)
 {
  cout << "CMyString(const CMyString &s)" << endl;
  m_pData = new char[strlen(s.m_pData)+1];
  strcpy(m_pData, s.m_pData);
 }

    // move構造函數
 CMyString(CMyString &&s)  // s是個臨時對象,右值引用
 {
  cout << "CMyString(CMyString &&s)" << endl;
  m_pData = s.m_pData;
  s.m_pData = NULL;
 }

    // 析構函數
 ~CMyString()
 {
  cout << "~CMyString()" << endl;
  delete [] m_pData;
  m_pData = NULL;
 }

    // 拷貝賦值函數
 CMyString &operator =(const CMyString &s)
 {
  cout << "CMyString &operator =(const CMyString &s)" << endl;
  if (this != &s)
  {
   delete [] m_pData;
   m_pData = new char[strlen(s.m_pData)+1];
   strcpy(m_pData, s.m_pData);
  }
  return *this;
 }

    // move賦值函數
 CMyString &operator =(CMyString &&s)  // s是個臨時對象,右值引用
 {
  cout << "CMyString &operator =(CMyString &&s)" << endl;
  if (this != &s)
  {
   delete [] m_pData;
   m_pData = s.m_pData;
   s.m_pData = NULL;
  }
  return *this;
 }

private:
 char *m_pData;
};

輸入圖片說明

###其餘:ui

什麼是左值、右值:this

C++左值與右值之道
C++左值與右值之間共同與不一樣點解析
C/C++左值性精髓(一) 左值的前世此生
C/C++左值性精髓(二)哪些表達式是左值,哪些是右值?.net

什麼是引用:unix

C++ 引用詳解code

什麼是右值引用:htm

右值引用
右值引用-維基百科對象

相關文章
相關標籤/搜索