mardi 24 avril 2018

Why does the unique_ptr have no overhead?

First take a look at what C++ Primer said about unique_ptr and shared_ptr:
$16.1.6. Efficiency and Flexibility

We can be certain that shared_ptr does not hold the deleter as a direct member, because the type of the deleter isn’t known until run time.

Because the type of the deleter is part of the type of a unique_ptr, the type of the deleter member is known at compile time. The deleter can be stored directly in each unique_ptr object.

So it seems like that the shared_ptr does not have a direct member of deleter,but unique_ptr does.However,the top-voted answer of another question says:

If you provide the deleter as template argument (as in unique_ptr) it is part of the type and you don't need to store anything additional in the objects of this type. If deleter is passed as constructor's argument (as in shared_ptr) you need to store it in the object. This is the cost of additional flexibility, since you can use different deleters for the objects of the same type.

The two quoted paragraph are totally conflicting,which makes me confused.What's more,many people says unique_ptr is zero overhead because it doesn't need to store the deleter as member.However,as we know, unique_ptr has a constructor of unique_ptr<obj,del> p(new obj,fcn),which means that we can pass a deleter to it,so unique_ptr seems to have stored deleter as a member. What a mess!

Aucun commentaire:

Enregistrer un commentaire