My homepage: http://www.tommstudio.com/
In Delphi programming, we need to avoid memory leaks by uninstalling all objects. However, if you are not careful in the program, it is easy to undo the same object multiple times, which will cause serious errors, causing the application to crash or even crash.
Please see the following program:
|
In the above example, an error will be generated when executing to Button3.Free, Button2 is cancelled when calling Button2.Free, but because Button2 is the host of Button3 and Button3 is also cancelled at the same time, the error inevitably occurs. Now.
To avoid the above error, there are two ways: First, remove all components to which the host is before it is removed. This method is very simple, just transfer Button2.Free and Button3.Free in the above example. Second, set the Button3 variable to nil before Button3.Free is executed. The procedure is as follows:
|
In the above program, setting Button3 to nil is to prevent the application from reusing the memory of the undefunct object. When calling the Free object method, it determines whether the object is nil. If not, the Free object method assumes that the object still exists, allocates memory to it using the object reference, and then calls Destroy to free the object memory and clears any related virtual object methods data table information. Destroy does not make any changes to the memory address where objects exist, so if you test the memory address after calling Destroy, it may still be valid. So when an object is called twice in the program without setting the object reference to nil, the object reference will still refer to the memory address occupied by the object before it was uninstalled, which is the reason for the error.
Of course, in the actual development process, most errors will not be so obvious, and the solution should be determined according to the specifics, and the problem will not be solved by adding a sentence so simply. Here I am just explaining a programming idea, which plays a role in attracting jade. The specific things depend on you to explore and accumulate in practice.