Pointer releasing memory for itself?

Started by
9 comments, last by vbisme 22 years, 5 months ago
quote:Original post by vbisme
delete pSCObj; is needed. This is the issue that I was trying to point out. How could pSCObj call a class that would ultimately execute "delete" upon itself?


It sounds like you want to have a class ''Foo'' which has allocated some memory, and you want the memory to be freed when you do a ''delete pSCObject''?

If yes, you need a destructor:

    // Called when deletion occurs - *before* the class is  // actually destroyed. Now you can get rid of any memory  // that the class allocated.  CSomeClass::~CSomeClass ()  {    Release();  }  


Now, there is no way, in C++, to make a class that will destroy itself when there are no more pointers to it (i.e., it has no references). You can make a ''fake'' pointer class and set it up so that it keeps count of the references to its target, those classes are known as smart pointers , for obvious reasons.

    class CSomeClass {    ...  }  class PSomeClass {    CSomeClass *pSC;    int *refCount;    ...  }  


You need to overload the constructors and destructor, and the * and = operators of PSomeClass to make sure that the reference count is kept correctly.

However, this method of reference counting isn''t perfect. It''ll keep an object alive if it has any references, even if those references are not accessible. For example, a node in a tree class might reference its parent and its children. The parent node would reference its children, including the original node. Although the tree might be inaccessible to the rest of the program, it still has references.

True garbage collection keeps a track of which objects are currently visible. Because C++ is not designed for gc it is extremely difficult to make a class heirarchy that uses it. It is best, therefore, to manually free memory when you can, and possibly use reference counting when you know that a reference cannot be recursive - I have a reference counting String class because I know that the string can''t contain a reference to itself.

All your bases belong to us
CoV

This topic is closed to new replies.

Advertisement