Understanding of deep copies and shallow copies:
Shallow copy: Is the same space that is shared between the copied object and the Copy object, that is, the pointer of two objects points to the same space.
Deep copy: The Copy object and the Copy object have their own space, the Copy object will open a new space, and then copy the object copied down.
Here are the implementations of deep and shallow copies
Class String
{
Public
Traditional notation
string& operator= (const string& s)//operator overloading
{
if (This! = &s)
{
/*delete[] _STR; First release the _STR, then open up space, then copy
_str = new Char[strlen (S._STR) + 1];
strcpy (_str, S._STR); * *
char* tmp = new Char[strlen (S._STR) + 1];
strcpy (TMP, S._STR); First use the temporary object tmp to open up space, when the string is copied to
Delete[] _STR; TMP, then release _STR, and finally assign the TMP address to _STR
_STR = tmp;
}
return *this;
}
String (char* str = "")//constructor
: _str (new Char[strlen (str) + 1])
{
strcpy (_str, str);
}
String (const string& s)//copy constructor
: _str (New Char[strlen (S._STR) + 1])
{
strcpy (_str, S._STR);
}
~string ()//destructor
{
if (_STR)//If _STR is not empty, use to release _str
{
Delete[] _STR;
}
}
Modern notation
String (const string& s)//copy constructor
: _str (NULL)
{
String tmp (S._STR); Creates a temporary object that copies a string to a temporary object, TMP
Swap (_STR, TMP._STR); Exchange _STR and Tmp._str pointer values, at which point TMP points to null
and _str points to the string
}
string& operator= (const string& s)//operator overloading
{
if (&s! = this)
{
String tmp (S._STR); Method Ibid.
Swap (_STR, TMP._STR);
}
return *this;
}
Overloading optimization for string& operator= (String s)//operator
{
Swap (_STR, S._STR); The above function is optimized, and a copy is made during the incoming object.
So the direct exchange of pointer values is possible.
return *this;
}
Private
char * _STR;
};
This article is from the "0-point Time" blog, please make sure to keep this source http://10741764.blog.51cto.com/10731764/1746898
About deep copy and shallow copy