C++学习笔记之析构函数(三法则)

定义:析构函数(destructor) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数。析构函数往往用来做“清理善后” 的工作(例如在建立对象时用new开辟了一片内存空间,delete会自动调用析构函数后释放内存)。

记住C++中有new,最终就要有对应的delete。

举例:

class TestClass

{

  public:

    TestClass();//构造函数

    ~TestClass();//析构函数

}

延伸:三法则

如果一个类需要程序员手动写析构函数,那么类一定需要拷贝构造函数和赋值操作符。

为什么呢?原因分析:如果需要手动写构造函数,那么类中必然出现了指针类型的成员并在构造函数中使用new操作符分配了内存。因此,为了避免前面提到的浅拷贝问题,程序员就一定需要定义拷贝构造函数和赋值操作符。

举例:

class TestClass

{

  private:

    string *m_pString;

    int m_i;

    double m_d;

  public:

    TestClass():m_pString(new string),m_i(0),m_d(0.0) //构造函数,初始化列表,new分配内存

    {

    }

    ~TestClass();

    TestClass(const TestClass &other);

    TestClass & operator = (const TestClass &other);

};

源文件中:

TestClass::~TestClass

{

  delete m_pString;

}

TestClass::TestClass(const TestClass &other)

{

  m_pString = new string;

  *m_pString = *(other.m_pString);

  m_i = other.m_i;

  m_d = other.m_d;

}

TestClass::TestClass & operator = (const TestClass &other)

{

  m_pString = new string;

  *m_pString = *(other.m_pString);

  m_i = other.m_i;

  m_d = other.m_d;

  return *this;

}

posted @ 2018-03-31 12:19  Mr.jason冯  阅读(186)  评论(0编辑  收藏  举报