Hi GURUs,
I have a problem that will tickle GURUs brain
Imagine I have the following class:Code:class clsA { public: clsB *pObjB; public: clsA() { pObjB = NULL; }; ~clsA() { if(pObjB) delete pObjB; }; };As you can see, GURU, pObjB is been created once. Since both pObjA1 and pObjA2 point to the same pObjB, it will cause the memory exception because pObjA2 will try to delete pObjB that has been deleted by pObjA1.Code:void main() { clsA *pObjA1 = new clsA(); clsA *pObjA2 = new clsA(); pObjA1->pObjB = new clsB(); pObjA2->pObjB = pObjA1->pObjB; delete pObjA1; //the destructor will delete pObjB delete pObjA2; //this will cause problem in the destructor since pObjB is not a valid pointer anymore (already been deleted previously by pObjA1 destructor) }
My question is, how can I check whether pObjB is a valid pointer before I delete it in the destructor?
Thanks for any help from GURU(s) in advance...
Cheers![]()





Reply With Quote