(4) Deep copy and shallow copy

Shallow copy : Values ​​can be assigned between objects of uniform type. If the values ​​of member variables of two objects are the same, the two objects are still two independent objects.

Under normal circumstances, there is no problem with shallow copy, but when there is a pointer in the class and the pointer points to the dynamically allocated memory space, the destructor performs dynamic memory release processing, which will cause memory problems

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class Person
{
    
    
public:
	Person() {
    
    }
	Person(char *name, int age)
	{
    
    
		m_name = (char*)malloc(strlen(name) + 1);
		strcpy(m_name,name);
		m_age = age;
	}

	// 系统默认拷贝构造,简单的值拷贝
	// 如果属性里有指向堆空间的数据,默认的拷贝构造函数会释放堆空间两次,导致空地址
    // 自定义拷贝构造函数,深拷贝
	Person(const Person&p) 
	{
    
    
		m_name = (char*)malloc(strlen(p.m_name) + 1);
		strcpy(m_name, p.m_name);
		m_age =p.m_age;
	}

	~Person()
	{
    
    
		cout << "执行析构函数...." << endl;
		if (m_name != nullptr)
		{
    
    
			free(m_name);
		}
	}
public:

	char *m_name;
	int m_age;
};

int main()
{
    
    
	Person p1((char*)("张三"),18);
	Person p2(p1);
}

Guess you like

Origin blog.csdn.net/qq_40329851/article/details/114293327