Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 663
Arun Avatar asked Apr 08 '14 03:04

Arun


People also ask

What happens when unique_ptr goes out of scope?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

What is unique_ptr used for?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another.


1 Answers

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.

like image 175
Florian Richoux Avatar answered Nov 15 '22 22:11

Florian Richoux