Modern deep copy writing and modern deep copy writing

Source: Internet
Author: User

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 ;}

  

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.