C++ notes-copy constructor

Copy constructor

effect

When an object is used to initialize another object, the copy constructor is automatically called

This is an ordinary int type initialization plus assignment

int a=15;
 int b=a;

The same reason

Animal a(6,60.5);
Animal b=a;  //调用拷贝构造函数

Features

  1. No overloaded form
  2. Must be used to initialize another object before calling
  3. If the programmer does not define a copy constructor, the system will automatically generate a copy constructor (shallow copy) for you. If the programmer customizes the destructor, the system will no longer automatically generate the default destructor
Animal(Animal &other)//浅拷贝 系统自动生成
{
    
    
	other中的数据赋值给this
}

Grammar rules

类名(类名 &)
{
    
    
	代码
}

Practical examples

We define an animal class whose private attribute is the age name. Then create an object a1 and initialize it. Then define an object a2, give him the attributes of a1, and see what happens.

class Animal
{
    
    
public:
	Animal(int _age,const char *_name)//构造函数
	{
    
    
		age=_age;
		name=new char[20];//给私有成员name分配堆空间
		strcpy(name,_name);
		cout<<"构造函数调用了"<<endl;
	}
	
	void show()	//打印
	{
    
    
		cout<<"目前的对象是: "<<this<<endl;
		cout<<"它里面的数据,年龄是: "<<age<<"  名字是: "<<name<<endl;
	}
	
	void setattr(int newage,const char *newname)//修改私有成员
	{
    
    
		age=newage;
		strcpy(name,newname);
	}
	
private:
	int age;
	char *name;
};
int main()
{
    
    
	//创建对象
	Animal a1(5,"旺财");
	
	//创建另外一个对象
	Animal a2=a1;  //调用系统默认生成的拷贝构造函数,该函数有bug

	a1.show();
	a2.show();
}

Insert picture description here
It can be seen that the value of a2 is the same as a1, which shows that the copy function automatically generated by the system exists.

But if we modify the value of a1, what will happen to a2

//修改a1的属性
	a1.setattr(6,"阿黄");
	cout<<"================修改之后=============="<<endl;
	a1.show();
	a2.show();

Insert picture description here
Why is the name of a2 also changed when you change the value of a1?

The reason is that our a1.name is created with heap space memory, and when the system calls the automatically generated copy function, it will only open up stack space memory for a2, and the memory of a2.name still points to a1.name Heap space. Insert picture description here
So this is the shortcoming of the copy function generated by the system, calledShallow copy

Deep copy

Animal(Animal &other)
{
    
    
	this->age=other.age;
	this->name=new char[20]; //单独给当前对象的name指针分配独立的堆空间
	strcpy(this->name,other.name);
	cout<<"拷贝构造函数被调用"<<endl;
}

As long as we can achieve the effect of separate separation.

The reason why the shallow copy cannot allocate heap space for the properties of the new object is because it does not know how much to allocate, so the programmer has to allocate it by himself.

Guess you like

Origin blog.csdn.net/weixin_46026429/article/details/108509568