Deep copy and shortest copy of C ++ Constructor

Source: Internet
Author: User

If there is no custom replication constructor, the system will create the default replication constructor. However, the default replication constructor created by the system will only execute "shortest copy ", values of the Data members of the Copied object are assigned to the newly created object. If the data member of this class has pointer members, the pointer of the new object is directed to the same address as the pointer of the Copied object. When you delete the pointer, duplicate delete operations may occur. The following is an example:


// Animal. h # include <string >#include <iostream> using namespace STD; Class tiger {protected: char * decription; public: Tiger (INT num, char *); tiger (Tiger & OBJ, int num); // deep copy Tiger (Tiger & OBJ); // shortest ~ Tiger (); void tigerrun ();};

// Animal. CPP # include "animal. H "Void Tiger: tigerrun () {cout <this-> decription <Endl;} Tiger: Tiger (INT num, char * des) {This-> decription = new char [num]; If (this-> decription = NULL) cout <"memory allocation failed" <Endl; strcpy (this-> decription, des);} // shortest copy Tiger: Tiger (Tiger & OBJ) {This-> decription = obj. decription;} // deep copy Tiger: Tiger (Tiger & OBJ, int num) {This-> decription = new char [num]; if (this-> decription = NULL) cout <"failed to allocate memory during copy ! "<Endl; strcpy (this-> decription, obj. decription);} Tiger ::~ Tiger () {Delete [] decription; cout <"Call destructor" <Endl ;}

# Include "anmal. H "int main () {tiger * Tg = new tiger (100," yellow ");/** the shortest copy will fail, if you want to run it correctly, comment out * because the decription members of TG and TG1 point to the same memory * after calling Delete, the memory is released * When the program ends, TG1 calls its own destructor again releasing this block of memory leads to an error */tiger TG1 (* TG ); // shortest tiger Tg2 (* TG, 50); // deep copy Delete TG; // release the memory allocated by new and return 0 ;}

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.