pointer copy error in c++ copy constructor

 First define a Human

 class Human {
public:  
	Human(); 
	Human(int age, int salary);
	Human(const Human& man);
	void setaddr(const char* addr);
	const char *getAddr()const;

private:
	string name = "Unknown";
	int age = 28;
	int salary;  
	char* addr = NULL;

}; 

Implement his member function


const char * Human::getAddr ()const {
	return addr;
}

Human::Human() { 
	name = "无名氏";
	age = 18;
	salary = 30000;
	strcpy_s(addr, ADDR_LEN, "China");
}



Human::Human(const Human& man) {
	salary = man.salary;
	age = man.age;
	name = man.name;
	addr = man.addr;

}

void Human::setaddr(const char* addr) {
	if (!addr) {
		return;
	}

	 strcpy_s(this->addr, ADDR_LEN,addr);  

}



Human::Human(int age, int salary)
{
	this->age = age;
	this->salary = salary; 
	this->name = "无名";
	strcpy((char*)addr,  "China");
}

main function

int main(void) {

	Human h1;
	Human h2(h1);
	 
	cout << "H1:" << h1.getAddr() << endl;

	cout << "H2:" << h2.getAddr() << endl;

	cout << "h1更改addr后" << endl;
 
 
	h1.setaddr("Franch");
	cout << "H1:" << h1.getAddr() << endl;

	cout << "H2:" << h2.getAddr() << endl;
	return 0;
}

main function

int main(void) {

	Human h1;
	Human h2(h1);
	 
	cout << "H1:" << h1.getAddr() << endl;

	cout << "H2:" << h2.getAddr() << endl;

	cout << "h1更改addr后" << endl;
 
 
	h1.setaddr("Franch");
	cout << "H1:" << h1.getAddr() << endl;

	cout << "H2:" << h2.getAddr() << endl;
	return 0;
}

Results of the

 There is a problem: obviously only the addr of h1 has been changed, but the addr of h2 has also changed, and it has also become Franch

This is because after the copy constructor is called, the addr of h1 and h2 points to the same memory, the addr of h1 changes this memory, and the addr of h2 is also this memory, so the addr of h1 and h2 are changed accordingly.

The solution is as follows:

Just open up a new memory for addr

void Human::setaddr(const char* addr) {
	if (!addr) {
		return;
	}

   this->addr = new char[ADDR_LEN];
	 strcpy_s(this->addr, ADDR_LEN,addr);  
 

}
Human::Human() { 
	name = "无名氏";
	age = 18;
	salary = 30000;
	 
	 addr = new char[ADDR_LEN];
	strcpy_s(addr, ADDR_LEN, "China");
}

 problem solved

Guess you like

Origin blog.csdn.net/m0_72703340/article/details/131800866