Copy construction and copy assignment------a somewhat difficult question.
Before we introduce, we need to first understand the difference between deep copy and shallow copy: What is deep copy, deep copy does not copy pointer, but the target object has a separate resource, the resource is copied from the meta-object, that is, to find the object's pointer, to copy its contents through the pointer;
What is a shallow copy, that is, the address of the assignment pointer, does not assign a pointer to the target, it is easy to throw a double free exception, that is, multiple targets pointing to the same memory;
Default copy constructor and default copy assignment function
If a class does not show the definition of a copy constructor and a copy assignment operator, the compiler provides one for it by default, but the function can only be shallow copies;
If a class has a member variable for a pointer and maintains a dynamically allocated memory resource with a pointer, define the copy constructor and copy assignment operator functions that support the deep copy for the class.
What's the next question?
Copy construction: T::t (T const& that) {} allocating resources, copying content
Copy Assignment:t& operator= (T const& r) {} Prevents self-assignment, allocates new resources, frees old resources, duplicates new content, and returns self-references;
To prevent misuse, we can also privatize the two to prevent misuse;
Below is a section of code for reference:
#include <iostream>
using namespace Std;
Class integer{
Public
Integer (int num): I (new int (num)) {}
Integer (integer& const that): I (new int (*that.i)) {}
integer& operatot= (Integer const& R) {
*I=*R.I;
return *i;
}
~integer () {
Delete I;
}
void const& GetValue () const{
cout<<*i<<endl;
}
Private
int* i;
Integer (const integer& that);
integer& operator (Integer const& R);
};
int main () {
Integer I1 (Ten), i2=i1;
I1.getvalue ();
I2.getvalue ();
return 0;
}
Copy construction and copy assignment of C + +