[ C\C++学习 ]之十八、C++11六大函数(构造函数,移动构造函数,移动赋值操作符,复制构造函数,赋值操作符,析构函数)(二)

2014-11-24 07:13:18 · 作者: · 浏览: 1
析构函数。

合成析构函数:

编译器总是会合成一个析构函数,合成析构函数按对象创建时的逆序撤销每个非static成员。要注意的是,合成的析构函数不会删除指针成员所指向的对象。

最后要注意的是:类如果需要析构函数,那么他肯定也需要复制构造函数和赋值操作符。

blog的最后给出完整的六大函数的代码。

#include 
  
   
#include 
   
     using namespace std; class Temp { public: Temp(const char* str = nullptr); Temp(Temp&& t); Temp& operator = (Temp&& t); Temp(const Temp& t); Temp& operator = (Temp& t); ~Temp(void); private: char *m_pData; }; Temp::Temp(const char* str) { if (!str) { m_pData = nullptr; } else { this->m_pData = new char[strlen(str) + 1]; strcpy(this->m_pData, str); } } Temp::Temp(Temp&& t) :m_pData(move(t.m_pData)) { t.m_pData = nullptr; } Temp& Temp::operator = (Temp&& t) { assert(this != &t); this->m_pData = nullptr; this->m_pData = move(t.m_pData); t.m_pData = nullptr; return *this; } Temp::Temp(const Temp& t) { if (!t.m_pData) { this->m_pData = nullptr; } else { this->m_pData = new char[strlen(t.m_pData) + 1]; strcpy(this->m_pData, t.m_pData); } } Temp& Temp::operator = (Temp &t) { if (this != &t) { delete[] this->m_pData; if (!t.m_pData) { this->m_pData = nullptr; } else { this->m_pData = new char[strlen(t.m_pData) + 1]; strcpy(this->m_pData, t.m_pData); } } return *this; } Temp::~Temp(void) { if (this->m_pData) { delete[] this->m_pData; this->m_pData = nullptr; } }
   
  


---2013.12.20