一、析構(gòu)函數(shù)的主要作用就是:釋放資源,避免內(nèi)存泄漏。
? ? ? ?如果類里面只用到的基本類型,如int char double等,系統(tǒng)的默認(rèn)析構(gòu)函數(shù)其實什么都沒有做
但如果你使用了其他的類如vector,string等,系統(tǒng)的默認(rèn)析構(gòu)函數(shù)就會調(diào)用這些類對象的析構(gòu)函數(shù)。
? ? ? ?平時使用中也一定要注意:
? ? ? ? ? ? ? ? ?對于指針型成員變量(動態(tài)分配內(nèi)存的)要先釋放內(nèi)存。
二、關(guān)于String類的例子:
class String
{
public:
? ? ~ String(void); // 析構(gòu)函數(shù)
? ? String(const char* str = NULL);//普通構(gòu)造函數(shù)
? ? String(const String &other);//拷貝構(gòu)造函數(shù)
? ? String &operate = (const String &other);//賦值操作
private:
? ? char * m_data;
}
// String 的析構(gòu)函數(shù)
String::~String(void)
{
? ? delete [] m_data;
}
// String 的普通構(gòu)造函數(shù)
String::String(const char *str)
{
? ? if(str==NULL)
? ? {
? ? ? ? m_data = new char[1];
? ? ? ? *m_data = ‘\0’;
? ? }
? ? else
? ? {
? ? ? ?int length = strlen(str);
? ? ? ?m_data = new char[length+1];
? ? ? ?strcpy(m_data, str);
? ? }
}
// 拷貝構(gòu)造函數(shù)
String::String(const String &other)
{
? ? int length = strlen(other.m_data);
? ? m_data = new char[length+1];
? ? strcpy(m_data, other.m_data);
}
// 賦值函數(shù)
String & String::operate =(const String &other)
{
? ? // (1) 檢查自賦值
? ? if(this == &other)
? ? return *this;
? ? // (2) 釋放原有的內(nèi)存資源
? ? delete [] m_data;
? ? // (3)分配新的內(nèi)存資源,并復(fù)制內(nèi)容
? ? int length = strlen(other.m_data);
? ? m_data = new char[length+1];
? ? ?strcpy(m_data, other.m_data);
? ? ?// (4)返回本對象的引用
? ? ?return *this;
}