Monday, April 30, 2012

#14 April 29

This week was entirely spent on learning about Handle classes in C++. This is a pretty interesting concept, and even more so, since the paper I reviewed a couple of weeks back is about smart pointers in C++ which can manage an underlying raw pointer -  which is almost exactly what the Handle classes do. 

We studied three different kinds of Handle classes - going from the simple Handle1, which is a very basic wrapper which doesn't even have support for de-referencing or indirection - implying that all the public API of the object of the underlying pointer will have to be replicated. The advantage, though is that the Handle1 objects can be looked upon as (polymorphic) objects and not pointers. A slightly more sophisticated version - Handle2 - overloads the de-reference and indirection pointers, thus saving us the trouble of replicating the public API in the handler class. But we lose the ability to look at Handle2 as an object - and it is now very clearly a pointer to the objects we want to use, however with memory management being handled internally. This resembles the unique_ptr in the C++ standard. It's also interesting to notice how the copy constructor works for these classes. Since they contain a pointer, we cannot simply copy over the pointer to the newly constructed class, because this could lead to delete being called twice on the same object. There are 2 solutions - one in which strict ownership is maintained, and another in which the object itself is copied. In the first one, the raw pointer "moves" to the newly constructed Handle, while the one in the old Handle is made NULL. If we want to keep using the old Handle, we can use the 2nd solution in which the pointer is cloned (the object it points to is copied, and the new pointer points to this new object). The final version of Handle is similar to C++'s shared_ptr. It uses reference counting so that multiple pointers could point to the same object and delete is called only when the last pointer to the object is deleted.

We used a variation of Handle1 for the Cell class in the project Life - and it allowed us to have a heterogeneous cell on the grid. By wrapping an underlying AbstractCell pointer, it allowed us to use polymorphism to have either a FredkinCell object or a ConwayCell object at a grid location.


No comments:

Post a Comment