While building my AOP engine, I needed to use containers that would hold polymorphic objects. Unfortunately for me, I had been programming in non-pointer based languages for so long that I have a serious case of brain-rot. So my first (and yes, really stupid attempt) at solving this problem was to use the following construct:
std::vector< Type >
Of course, this exposed me to the dreaded slicing problem since STL uses a value-type idiom for its container elements. So, I quickly resorted to my old friend, the pointer, since I needed to bang out a bunch of code in a hurry for my demonstration at VS Live!
std::vector< Type* >
Now that I’ve got some time carved out to refactor my code, I want to get rid of this ugliness. So, I proceeded to look at various smart pointer implementations:
std::vector< SmartPtr< Type > >
However, nothing in C++ is ever as simple as it appears. I had to contend with issues like whether the smart pointer would copy the object when assigning to the container, or whether I could get away with a reference counted smart pointer.
In the end, I decided to go with the Boost library’s shared_ptr implementation. So far so good.
Here’s two papers that I found through a Google search that have helped influence my thinking in this area.