Why is there apparently no need for a virtual destructor when using smart pointers?

Consider the below code:

#include <iostream>
#include <memory>

struct Base
{
    ~Base() {std::cout << "~Base()" << std::endl;}
};

struct Derived : Base
{
    ~Derived() {std::cout << "~Derived()" << std::endl;}
};

int main()
{
    // why does the right destructor is called at program exit?
    std::shared_ptr<Base> sptrBase{std::make_shared<Derived>()}; 
}

      

which outputs

~ Derived ()

~ Base ()

There is Base

no virtual destructor in my class . However, when using the object Derived

with a smart pointer to the Base

correct handle ~Derived()

, it seems to be called correctly on program exit. Why is this happening (instead of undefined behavior)? Is this because the type Derived

is somehow "written" when the result is std::make_shared<Derived>()

converted to std::shared_ptr<Base>

? Or is it plain UB?

+3


source to share





All Articles