c++polymorphismsmart-pointersrule-of-zero

C++ Rule of Zero : polymorphic deletion and unique_ptr behavior


In the recent overload journal under the topic Enforcing the rule of zero, the authors describe how we can avoid writing the Rule of five operators as the reasons for writing them are:

  1. Resource management
  2. Polymorphic deletion

And both these can be taken care of by using smart pointers.

Here I am specifically interested in the second part.

Consider the following code snippet:

class Base
{
public:
    virtual void Fun() = 0;
};


class Derived : public Base
{
public:

    ~Derived()
    {
        cout << "Derived::~Derived\n";
    }

    void Fun()
    {
        cout << "Derived::Fun\n";
    }
};


int main()
{
    shared_ptr<Base> pB = make_shared<Derived>();
    pB->Fun();
}

In this case, as the authors of the article explain, we get polymorphic deletion by using a shared pointer, and this does work.

But if I replace the shared_ptr with a unique_ptr, I am no longer able to observe the polymorphic deletion.

Now my question is, why are these two behaviors different? Why does shared_ptr take care of polymorphic deletion while unique_ptr doesn't?


Solution

  • You have your answer here: https://stackoverflow.com/a/22861890/2007142

    Quote:

    Once the last referring shared_ptr goes out of scope or is reset, ~Derived() will be called and the memory released. Therefore, you don't need to make ~Base() virtual. unique_ptr<Base> and make_unique<Derived> do not provide this feature, because they don't provide the mechanics of shared_ptr with respect to the deleter, because unique pointer is much simpler and aims for the lowest overhead and thus is not storing the extra function pointer needed for the deleter.