Home >Backend Development >C++ >Can shared_ptr Work Without Polymorphic Class Virtual Destructors?

Can shared_ptr Work Without Polymorphic Class Virtual Destructors?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 11:45:11130browse

Can shared_ptr Work Without Polymorphic Class Virtual Destructors?

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 sp (new Derived)), the templated constructor with Y=Derived is invoked. This constructor creates the deleter object with specific knowledge of the Derived class. Upon reaching zero reference count, this deleter is used to safely dispose of the Derived instance, even without a virtual destructor in the Base class.

C 11 Standard Requirements

The C 11 standard explicitly defines the requirements for this constructor:

  • The pointer p must be convertible to T* and Y must be a complete type.
  • The expression "delete p" must be well-formed, have well-defined behavior, and not throw exceptions.

For the destructor:

  • If shared_ptr is empty or shares ownership, there are no side effects.
  • If shared_ptr owns an object with a deleter d, d(p) is called.
  • Otherwise, if shared_ptr owns a pointer p, "delete p" is invoked.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn