如果需要实现深拷贝(deep copy),就需要自定义拷贝构造函数

将指针类型的成员变量所指向的内存空间,拷贝到新的内存空间

示例:

class Car {
	int m_price;
	char *m_name;

public:
	Car(int price = 0, const char *name = NULL) :m_price(price) { 
		if (name == NULL) return;

		// 申请堆空间存储字符串内容
		this->m_name = new char[strlen(name) + 1]{};
		// 拷贝字符串内容到堆空间(string copy)
		strcpy(this->m_name, name);

		cout << "Car(int, const char *)" << endl;
	}
    // 拷贝构造函数:防止堆空间多次free的问题
	Car(const Car &car) :m_price(car.m_price) {
		if (car.m_name == NULL) return;

		// 申请堆空间存储字符串内容
		this->m_name = new char[strlen(car.m_name) + 1]{};
		// 拷贝字符串内容到堆空间(string copy)
		strcpy(this->m_name, car.m_name);

		cout << "Car(const Car &car)" << endl;
	}
    
    // 需要注意:申请的堆空间需要手动释放
	~Car() {
		if (this->m_name == NULL) return;

		delete[] this->m_name;
		this->m_name = NULL;

		cout << "~Car()" << endl;
	}

	void display() {
		cout << "price is " << this->m_price << ", name is " << this->m_name << endl;
	} 
};

C语言复习

// \0表示这个字符串结束了
char name[] = { 'b', 'm', 'w', '\0' };
cout << name << endl; // 打印结果 bmw
cout << strlen(name) << endl; // 3 内存实际上会多占一个字节
const char *name = "bmw";

使用堆空间创建一个car对象

int main() {
    char name[] = { 'b', 'm', 'w', '\0' };
    Car *car = new Car(100, name);
    car->display();
    delete car;
    
    getchar();
	return 0;
}

使用栈空间拷贝对象

Car car1(100, "bmw");

// 将car1的内存空间(8个字节)覆盖car2的内存空间(8个字节)
Car car2 = car1;

cout << &car1 << endl;
cout << &car2 << endl;