Such as:
String A ("Sky1"), B ("Sky2");
b = A;
The program creates two objects at run time, A and B, respectively, and then calls the constructor. When executing "b=a", because there is no user-defined assignment operator function, then the program automatically calls the default assignment function, two pointers to the same memory, "Sky2" the memory of this space should be inaccessible. When the program executes to the destructor, releases the memory, revokes b, releases the memory that B points to, and then releases a, however, although the pointer to a is still in, however, because it is the same memory as the B point, and because the memory space of "Sky1" is released when the destructor B is executed, now execution A is released, Unable to find the memory to be freed, and the memory that the previous B pointed to has not been released, the destructor cannot find where it is? There is the so-called "pointer hanging Problem".
Resolved as follows:
#include <iostream>#include<string.h>using namespacestd;classstring{ Public: String (intSize =1,Char* str =" /") {ptr=New Char[size]; strcpy (PTR,STR); This->size =size; } String (ConstString &obj) {Size=obj.size; PTR=New Char[size]; strcpy (PTR,OBJ.PTR); } Stringoperator=(ConstString & obj)//avoid the problem of pointer hanging{size=obj.size; delete [] ptr;//release the original memory firstPTR =New Char[Size];//to generate new memorystrcpy (PTR,OBJ.PTR);//Copy String return* This; } ~String () {delete [] ptr; }Private : Char*ptr; intsize;};intMain () {String str1 (Ten,"Hangzhou"), STR2 (Ten,"HDU"); STR2= STR1;//easy to cause the needle to hang return 0;}
C + + pointer hanging (assignment operator overloading)