[C++ SDK] Freeing custom grips


(Menno Deij - van Rijswijk) #1

I noticed that I need to track custom grips that I create to be able to free them, because in the destructor of the CRhinoObjectGrips derived object the m_grip_list is already empty.

If I don’t free them, memory leaks are reported.

class CMyGrip : public CRhinoGripObject
{};
class CMyGrips : public CRhinoObjectGrips
{
    ~CMyGrips();
    bool CreateGrips(const ON_Surface& srf);
};
CMyGrips::CreateGrips(const ON_Surface& srf)
{
    for(int i = 0; i < grip_count; ++i)
        m_grip_list.add(new CMyGrip());
}

CMyGrips::~CMyGrips()
{
    // at this point the m_grip_list is empty
    for(int i = 0; i < m_grip_list.Count(); ++i)
    {
        CRhinoGripObject* pGrip = m_grip_list[i];
        if (pGrip) delete pGrip;
    }
}

(Dale Fugier) #2

The destructor for CRhinoRectangleGrips will not delete the members of CRhinoRectangleGrips::m_grip_list. But you should zero out the list during the destruction of your CRhinoRectangleGrips derived object so members that have been deleted are not reference by the base class destructor.

Here is an example:

https://github.com/mcneel/Rhino5Samples_CPP/blob/master/SampleCustomGrips/RhinoRectangleObject.cpp


(Menno Deij - van Rijswijk) #3

The only reason the example works IMHO is not that memory gets zero’d, but because the m_rectangle_grips array is freed automatically when the object is destroyed.

In my example you will see that I use the new operator to make grips. This means that I need to free them too. I can’t do that in the destructor because at that point m_grip_list is empty. Therefore I need to keep track of the created objects in e.g. a std::vector<CMyGrip*> that I use in the destructor to free the pointers contained in it.