Garbage collection is available in both Java and C #, and programmers are freed from complex memory management by automatically recycling garbage collection after allocating a piece of memory. This is a great advantage of Java and C #. C + + programmers in the allocation of a section of memory with new, you must also use Delete to release, otherwise it will cause a resource leak. Therefore, some C + + books often warn programmers: to develop good habits, new and delete to appear in pairs, always remember to release memory back to the system. But is it just that simple?
Often, in the process of using C + +, we encounter the following scenario:
class A
{
public:
A();
~A();
SetNextPtr(A* Ptr)
{pNext=Ptr;}
private:
A * pNext;
}
In general, in order not to cause a memory leak, we will release Pnext in the destructor, as follows:
A::~A()
{
if(pNext)
delete pNext;
pNext=NULL;
}
For the general situation, this is enough, but in some cases, this can be problematic, as follows:
A *ptrB = new A;;
A *ptrA = new A;
ptrB->SetNextPtr(ptrA);
ptrA->SetNextPtr(ptrB);
Delete ptrb;
This can be problematic, because these pointers are connected to a loop, and regardless of the point at which the deletion begins, it causes a pointer to be deleted more than two times, which causes the program to throw an exception. Of course, there are some ways to solve this problem, but I would like to explain: for C + + programmers, it is not difficult to develop a good habit, it is difficult sometimes this will bring you into a logical confusion, add some unnecessary trouble, sometimes even overwhelmed.
But how to solve this problem? If C + + also has the function of garbage collection, then, of course, this problem is solved. But C + + is a compiled language and does not have this functionality. I've been thinking about this for a long time, trying to figure out a way to get myself out of this mess. Until recently I began to learn generic programming, and after seeing the introduction of smart pointers, I had a flash of inspiration and finally found a way to solve the problem.