The difference in the usage of the title copy constructor and assignment constructor compiler

The difference between title copy constructor and assignment constructor

Copy constructor in c++
For example, look at the following code for testing purposes, all the functions of the class are written in a cpp file.

#include
#include<Windows.h>

using namespace std;

class Test{

public:

Test(){

}

Test(const Test &other){

	cout << "调用拷贝构造" << endl;
}

Test &operator=(const Test &other){

	cout << "调用赋值构造" << endl;

	return *this;
}

};

int main(void){

Test v1;

Test v2(v1);//调用拷贝构造函数

v2 = v1;//调用赋值构造函数

system("pause");
return 0;

}
Summary in terms of appearance: The so-called assignment constructor is to perform assignment operations on two existing objects.
For example: Test v1, v2;
v1=v2//This is the assignment constructor
Test v3(v1); //When creating a non-existent object, call the copy constructor as described above.

Note: If there is a defined pointer inside, then there is the problem of memory release.
Take the definition of a private member
char *name; as an example

There is no need to release the memory in the copy constructor, but need to release the memory in the assignment constructor.
(Vector is not a vector, the former is a capital V! T is a template class)

Vector& Vector::operator=(const Vector&object){

if (m_base){
	delete[] m_base;
	
}
this->m_len = object.m_len;
this->m_base = new T[m_len];
	
	
	for (int i = 0; i < m_len; i++){
	
		m_base[i] = object.m_base[i];//why?
	
	}
return *this;

}
Simple understanding, the assignment constructor is the assignment operation of two existing objects, when the need to release the memory. The copy constructor is to copy an existing object to an upcoming object. Of course, this upcoming object does not need to be released. Because he has not allocated memory, do I still need to release the memory? The answer is definitely not needed.
//There is no release of memory judgment here!
Vector::Vector(const Vector&object){

cout << "调用拷贝构造函数" << endl;
m_len = object.m_len;
m_base = new T[m_len];
for (int i = 0; i < m_len; i++){

m_base[i] = object.m_base[i];
}

}

Guess you like

Origin blog.csdn.net/weixin_45825875/article/details/106039077