Object lifecycle management is the most important part of the C ++ project. This kind of problem has always been found in the "game programming essence" (GPG) series.Article. For example, book 3, 1.5 smart pointer Based on handles, and book 4, 1.7, weak references and empty objects. In gpg4 1.7CodeSome problems are found. If the original code is put into the actual project, the results will be very bad. Here I will mention
The original Article handles pointer packaging as follows:
Template <class resourcetype> class resptr
{
Public:
// Some Constructors
Resptr (const resptr <resourcetype> & resptr );
Explicit resptr (resourcetype * PRES );
Resptr (resourceptrholder * pholder = NULL );
Public:
// Structure
~ Resptr ();
PRIVATE:
// Use this middle layer to encapsulate the pointer
Resourceptrholder * m_presholder;
}
Class resourceptrholder
{
Public:
Resourceptrholder (iresource * P): Pres (p ){}
~ Resourceptrholder ();
// Put the user object pointer here
Iresource * pres;
};
Template <class resourcetype> resptr <resourcetype>: resptr (resourcetype * PRES)
{
M_presholder = new resourceptrholder (PRES); // when encapsulating native pointers, a new resourceptrholder object is generated in heap.
}
Template <class resourcetype> resptr <resourcetype> ::~ Resptr ()
{// Empty destructor
}
Other resptr codes are omitted, but it is worth mentioning that there is no Delete m_presholder words...
That is to say, if resptr is used directly, A resourceptrholder object is leaked once.
The Code provides another set of pointer packaging versions for reference counting. resourceptrholder uses Delete this to destroy the memory. But there is still a problem:
Resourceptrholder ::~ Resourceptrholder ()
{
Delete pres;
}
First, iresource makes mandatory provisions on Pointer types to be managed externally. Must be a class derived from iresource. The second step is to delete the content of an external incoming object pointer to be managed during the holder analysis. This tough strategy will cause huge exceptions wherever it is put. Even if the reference counting version is used, you can delete yourself after the holder count is 0. Deleting managed objects is also a black hole for the outside.
1.7 The quality of the Code is shocking. I still don't know how many similar