samedi 11 avril 2020

How to avoid pointing to deallocated memory (dangling pointers) in classes with pointer members

When an object has a pointer member, the pointer may point to the part of memory that is not owned by the object. Thus, it may be deallocated without informing the object and cause a dangling pointer (and abundant headaches to debug). For example, let's say I have an object of type ClassHasPointer that has a member variable m_memberPtr of type AnotherClass *.

class ClassHasPointer 
    {
      public:           
             void setMember(AnotherClass* anotherObj) { m_memberPtr = anotherObj; }
             AnotherClass* getMember() { return m_memberPtr; }

      private:
             AnotherClass* m_memberPtr = nullptr;
    }

Now let's say I have an object of AnotherClass called anotherObj that I have defined and used elsewhere in the program. Now, I decide to initialize an object of ClassHasPointer:

ClassHasPointer A;
A.setMember(&anotherObj); // m_memberPtr points to anotherObj

Now, if anotherObj goes out of scope or gets deallocated in any part of the program, m_memberPtr is pointing to junk, thus it's a dangling pointer:

AnotherClass* aBadPtr = A.getMember(); // anotherObj was destroyed, dangling pointer!

We tend to utilize pointers as member variables frequently in classes. I think everytime we do that, it comes with a caveat that the class may not own the data it's pointing to. My questions is how can we ensure we are not accessing the data while it's deallocated without having to unnecessarily copying the data it's pointing to? More importantly, in general, what are the good practices/guidelines/design patterns to avoid this pitfall?

Aucun commentaire:

Enregistrer un commentaire