Shared_Ptr Implementation Without Polymorphic Class Virtual Destructor
In the debate between Armen Tsirunyan and Daniel Lidström on the necessity of virtual destructors for shared_ptr implementation, it is indeed possible to design a shared_ptr that does not require such destructors.
Technical Implementation
The key to this implementation lies in type erasure. Shared_ptr manages not only reference counters but also a deleter object stored in the same memory block. The type of this deleter is distinct from that of shared_ptr, allowing for flexibility in managing objects with different dynamic types.
A templated constructor is introduced:
template<class T> class shared_ptr { public: ... template<class Y> explicit shared_ptr(Y* p); ... };
When constructing a shared_ptr with a pointer of a derived class (e.g., shared_ptr
C 11 Standard Requirements
The C 11 standard explicitly defines the requirements for this constructor:
For the destructor:
Thus, the shared_ptr implementation utilizes type erasure and carefully manages deleters to effectively dispose of objects with differing dynamic types, even without requiring virtual destructors in polymorphic classes.
The above is the detailed content of Can shared_ptr Work Without Polymorphic Class Virtual Destructors?. For more information, please follow other related articles on the PHP Chinese website!