The Smart Pointer Implementation: SmartPtr<T>

The SmartPtr class is described in IpSmartPtr.hpp. It is a template class that takes care of counting references to objects and deleting them when not references anymore. Instead of pointing to an object with a raw C++ pointer (e.g. HS071_NLP*), we use a SmartPtr. Every time a SmartPtr is set to reference an object, it increments a counter in that object (see the ReferencedObject base class if you are interested). If a SmartPtr is done with the object, either by leaving scope or being set to point to another object, the counter is decremented. When the count of the object goes to zero, the object is automatically deleted. SmartPtr's are very simple, just use them as you would use a standard pointer.

It is very important to use SmartPtr's instead of raw pointers when passing objects to IPOPT. Internally, IPOPT uses smart pointers for referencing objects. If you use a raw pointer in your executable, the object's counter will NOT get incremented. Then, when IPOPT uses smart pointers inside its own code, the counter will get incremented. However, before IPOPT returns control to your code, it will decrement as many times as it incremented earlier, and the counter will return to zero. Therefore, IPOPT will delete the object. When control returns to you, you now have a raw pointer that points to a deleted object.

This might sound difficult to anyone not familiar with the use of smart pointers, but just follow one simple rule; always use a SmartPtr when creating or passing an IPOPT object.