Modern deep copy writing and modern deep copy writing
The modern method of deep copy is simpler than the traditional method. That is, an intermediate object tmp is created. Its _ str Pointer Points to s. _ str, exchange tmp. after _ str and _ str, _ str points to s. _ str: if the copy is out of the scope, tmp will automatically call its destructor, releasing the memory that the original _ str points to, which also achieves our desired effect.
For example:
# Include <iostream> using namespace std; class String {public: String (char * str = "") // strlen (NULL) is not allowed ): _ str (new char [strlen (str) + 1]) {strcpy (_ str, str);} String (const String & s): _ str (NULL) {String tmp (s. _ str); swap (_ str, tmp. _ str);} String & operator = (const String & s) {if (this! = & S) {String tmp (s. _ str); swap (_ str, tmp. _ str);} return * this ;}~ String () {delete [] _ str;} private: char * _ str ;};
Of course, the value assignment operator overload here can be further optimized:
String & operator = (String s) // optimization (s cannot be referenced, otherwise it will change the value of the real parameter) (Here s is a copy of the real parameter) {swap (_ str, s. _ str); return * this ;}