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