January 2019
Intermediate to advanced
512 pages
14h 5m
English
Let's finally see how std::shared_ptr does its magic. We will do it with a simplified example of a smart pointer that focuses specifically on the type erasure aspect. It should not surprise you to learn that this is done with a combination of generic and object-oriented programming:
template <typename T>class smartptr { struct deleter_base { virtual void apply(void*) = 0; virtual ~deleter_base() {} }; template <typename Deleter> struct deleter : public deleter_base { deleter(Deleter d) : d_(d) {} virtual void apply(void* p) { d_(static_cast<T*>(p)); } Deleter d_; }; public: template <typename Deleter> smartptr(T* p, Deleter d) : p_(p), d_(new deleter<Deleter>(d)) {} ~smartptr() { d_->apply(p_); delete d_; } T* operator->() ...