To illustrate what is Pointer suspension, let's consider the following simple String-type program example:
# Include "string. h"
Class String
{
Char * p;
Int size;
Public:
String (int sz)
{
P = new char [size = sz];
}
~ String ()
{
Delete p;
}
};
Void main ()
{
String s1 (10 );
String s2 (20 );
S1 = s2;
}
In the upper-column program, we did not overload the value assignment operator for the String class. Therefore, the value assignment expression s1 = s2 is to use the default value assignment operator to assign values to s1 by s2, in this way, the data members (character pointers p and INTEGER size) of the object s2 are copied to the corresponding data members of s1 one by one, in this way, the original value of the data member of S1. Because both s1.p and s2.p have the same value and point to the string of s2, the memory zone that s1.p originally points to is not released, but cannot be reused after being blocked. This is a so-called pointer suspension problem.
The more serious problem is that, because both s1.p and s2.p point to the same memory zone, when the lifetime of the s1 and s2 objects ends (when the main function stops running ), two destructor (s1 .~ String and s2 .~ String), so that the memory is released twice, which is a very serious error.
Some readers may find it hard to understand the above example. Next we will explain under what circumstances pointer suspension may occur through a simple and easy-to-understand example.
# Include "stdafx. h"
# Include "iostream. h"
Void main ()
{
Int * p1 = new int (8); // allocate a space for integer data in the memory and give the first address to P1
Int * p2 = new int (9); // allocate a space for integer data in the memory and give the first address to P2
Cout <p1 <"/n"; // output the address of the memory unit pointed to by P1
Cout <p2 <"/n"; // output the address of the memory unit pointed to by P2
Cout <* p1 <"/n"; // output the content in the memory unit pointed to by P1
P1 = p2; // assign P2 to P1, that is, P1 also points to the memory unit pointed to by P2
Cout <p1 <"/n ";
Cout <p2 <"/n"; // The output shows that P1 and P2 point to the same address unit.
Cout <* p1 <"/n ";
Cout <* p2 <"/n"; // The output shows that P1 and P2 point to the same address unit.
Delete p1; // actually releases the memory unit pointed to by P2, but the address pointed to by P1 cannot be found again
// Failed to release because we didn't save it beforehand. This causes the pointer suspension problem.
Delete p2; // release the memory unit pointed to by P2 again, which produces a serious error.
}
Because pointer suspension is an easy-to-detect error when using pointers, it is recommended that you practice it on your computer to avoid serious consequences caused by such errors in future development.