common interview question.
This mega-pattern is present in 90% of java and c# classes, and also very common in c++. Important
data structure classes using pointer fields include vectors, strings, hashtables and most STL or boost containers. These containers can grow, so the payload must live on heap, which requires heap pointer as data field.
Three common choices for a heap pointer member variable:
- Raw pointer — default and most popular choice
- shared_ptr — often a superior choice
- char pointer, usually a c-str as a field.
In each case, we worry about
- construction of this field
- freeing heap memory
- what if the pointee is not on heap?
- copy control of this field
- ownership of the pointer
- when to return raw ptr and when to return a smart ptr, from a member function
— shared_ptr as field
I read somewhere that shared_ptr field offers exception safety, automatic delete, default synthesized dtor, copier, op=().
However, this technique is unpopular partly because readers of the class source code prefers transparency and familiarity.
As author of the host class, I won’t decide to leave the big4 as default. However, if I forget to implement one of the big4, the default is more likely to be safe and acceptable.