【C++】何时需要自定义拷贝构造函数和赋值符
生活随笔
收集整理的這篇文章主要介紹了
【C++】何时需要自定义拷贝构造函数和赋值符
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先來說結論:當類中有指針類型成員變量的時候,一定要自定義拷貝構造和賦值運算符
原因:當我們在有指針類成員變量的時候,還是用默認拷貝構造函數(拷貝構造函數執行的時候會調用賦值符),默認賦值為淺拷貝,會導致兩個對象指向同一塊堆區空間,在最后析構的時候導致內存二次析構而出錯!
下面來看一下代碼的示例:
#include<iostream>
using namespace std;
#include<string.h>#define SIZE 10class SeqList
{int *data;int maxsize;int cursize;public:SeqList() :data(NULL), maxsize(SIZE), cursize(0){data = (int*)malloc(sizeof(int) * maxsize);}~SeqList() {free(data);data = NULL;}
};int main()
{SeqList seqa;SeqList seqb(seqa);return 0;
}
大家來看一下上述代碼的分析以及錯誤原因:
?現在我們來自定義拷貝構造函數和賦值運算符:
拷貝構造函數:
SeqList(const SeqList& Seq)
{maxsize = Seq.maxsize;cursize = Seq.cursize;data = (int*)malloc(sizeof(int) * Seq.maxsize);//得在堆區重新申請一塊空間來確保不會二次析構memcpy(data, Seq.data, sizeof(int)* Seq.cursize);//將seq堆區的東西拷貝
}
下面來看一下為什么還需要對賦值運算符進重寫:
#include<iostream>
using namespace std;
#include<string.h>#define SIZE 10class SeqList
{int *data;int maxsize;int cursize;public:SeqList() :data(NULL), maxsize(SIZE), cursize(0){data = (int*)malloc(sizeof(int) * maxsize);}~SeqList() {free(data);data = NULL;}
};int main()
{SeqList seqa;SeqList seqb;seqa = seqb;return 0;
}
我們來分析一下這里錯誤的原因:
下面我們來自定義等號運算符:
SeqList& operator=(const SeqList& Seq){if (this != &Seq){free(data); //將內存泄漏那一塊提前給釋放了data = (int*)malloc(sizeof(int) * Seq.maxsize);memcpy(data, Seq.data, sizeof(int) * Seq.cursize);maxsize = Seq.maxsize;cursize = Seq.cursize;}return *this;}
下面將代碼整合起來:
#include<iostream>
using namespace std;
#include<Cstring>#define SIZE 10class SeqList
{int *data;int maxsize;int cursize;
private:public:SeqList() :data(NULL), maxsize(SIZE), cursize(0){data = (int*)malloc(sizeof(int) * maxsize);}SeqList(const SeqList& Seq){maxsize = Seq.maxsize;cursize = Seq.cursize;data = (int*)malloc(sizeof(int) * Seq.maxsize);memcpy(data, Seq.data, sizeof(int)* Seq.cursize);}SeqList& operator=(const SeqList& Seq){if (this != &Seq){free(data);data = (int*)malloc(sizeof(int) * Seq.maxsize);memcpy(data, Seq.data, sizeof(int) * Seq.cursize);maxsize = Seq.maxsize;cursize = Seq.cursize;}return *this;}~SeqList() {free(data);data = NULL;}
};int main()
{/*SeqList seqa;SeqList seqb(sqea);*/SeqList seqa;SeqList seqb;seqa = seqb;return 0;
}
總結一下,當類中有指針類型成員變量的時候,一定要自定義拷貝構造和賦值運算符,否則會造成內存泄漏或者二次析構!
總結
以上是生活随笔為你收集整理的【C++】何时需要自定义拷贝构造函数和赋值符的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多囊卵巢吃达英35瘦了
- 下一篇: 【C++】继承