Home >Backend Development >C++ >Can `shared_ptr` Manage `Derived` Objects Without a Virtual Destructor in `Base`?

Can `shared_ptr` Manage `Derived` Objects Without a Virtual Destructor in `Base`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 20:53:10456browse

Can `shared_ptr` Manage `Derived` Objects Without a Virtual Destructor in `Base`?

Shared_Ptr and Polymorphism Without Virtual Destructors

In a recent debate, Daniel Lidström asserted that a shared_ptr constructed with new Derived does not mandate a virtual destructor in Base. This article investigates the feasibility of such an implementation.

Implementing Shared_Ptr Without Virtual Destructors

The key to this implementation lies in type erasure. Shared_ptr stores more than just reference counters; it includes a deleter (stored as part of the data structure) that handles object destruction. This deleter can be of any type, allowing for customization beyond the scope of T (the template type of shared_ptr).

Customization for Derived Classes

When creating a shared_ptr from a Derived object, a templated constructor is invoked, allowing specification of the concrete type Derived. The constructor creates the necessary deleter with knowledge of the dynamic type, ensuring proper object destruction even without a virtual destructor in Base.

Example Implementation

template<class T>
class shared_ptr
{
public:
   ...
   template<class Y>
   explicit shared_ptr(Y* p);
   ...
};

The above constructor allows the creation of a shared_ptr from a Derived object.

C 11 Standard Requirements

The C 11 standard explicitly requires this behavior:

  • The templated constructor must ensure that the expression delete p has well-defined behavior, even without a virtual destructor in T.
  • If the shared_ptr owns an object without a deleter, it should call delete p.

The above is the detailed content of Can `shared_ptr` Manage `Derived` Objects Without a Virtual Destructor in `Base`?. 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