深拷贝与浅拷贝
深浅拷贝是面试经典问题,也是常见的一个坑
浅拷贝:简单的赋值拷贝操作
深拷贝:在堆区重新申请空间,进行拷贝操作
示例:
class Person {public://无参(默认)构造函数Person() {cout << "无参构造函数!" << endl;}//有参构造函数Person(int age ,int height) {cout << "有参构造函数!" << endl;m_age = age;m_height = new int(height);}//拷贝构造函数Person(const Person& p) {cout << "拷贝构造函数!" << endl;//如果不利用深拷贝在堆区创建新内存,会导致浅拷贝带来的重复释放堆区问题m_age = p.m_age;m_height = new int(*p.m_height);}//析构函数~Person() {cout << "析构函数!" << endl;if (m_height != NULL){delete m_height;}}public:int m_age;int* m_height;};void test01(){Person p1(18, 180);Person p2(p1);cout << "p1的年龄: " << p1.m_age << " 身高: " << *p1.m_height << endl;cout << "p2的年龄: " << p2.m_age << " 身高: " << *p2.m_height << endl;}int main() {test01();system("pause");return 0;}
总结:如果属性有在堆区开辟的,一定要自己提供拷贝构造函数,防止浅拷贝带来的问题
//This is an error program#include <iostream>using namespace std;class Person {public:Person() {m_age = 0;m_ph = NULL;cout << "Default Construct function" << endl;}Person(int age,int h) {cout << "Person's Parametric Constructed function" << endl;m_age = age;m_ph = new int(h);}~Person() {//堆区开辟的数据释放,在析构函数中释放if (m_ph != NULL) {delete m_ph;m_ph = NULL;}cout << "Person's Destruct function" << endl;}int m_age;int* m_ph;};void exam() {Person p1(18,160);cout << "Age of p1 is " << p1.m_age << endl;cout << "height of p1 is " << *p1.m_ph << endl;Person p2(p1);cout << "Age of p2 is " << p2.m_age << endl;cout << "height of p2 is " << *p2.m_ph << endl;}int main() {exam();}
#include <iostream>using namespace std;class Person {public:Person() {m_age = 0;m_ph = NULL;cout << "Default Construct function" << endl;}Person(int age,int h) {cout << "Person's Parametric Constructed function" << endl;m_age = age;m_ph = new int(h);}Person(const Person& p) {cout << "Person's copy function" << endl;m_age = p.m_age;//m_ph = p.m_ph; // This is how the complier does;m_ph = new int(*p.m_ph);//Problem solved}~Person() {//堆区开辟的数据释放,在析构函数中释放if (m_ph != NULL) {delete m_ph;m_ph = NULL;}cout << "Person's Destruct function" << endl;}int m_age;int* m_ph;};void exam() {Person p1(18,160);cout << "Age of p1 is " << p1.m_age << endl;cout << "height of p1 is " << *p1.m_ph << endl;Person p2(p1);cout << "Age of p2 is " << p2.m_age << endl;cout << "height of p2 is " << *p2.m_ph << endl;}int main() {exam();}
