vendredi 2 janvier 2015

Deleter type in unique_ptr vs. shared_ptr

I thought it is very curious when I discovered that the standard defines std::unique_ptr and std::shared_ptr in two totally different ways regarding a Deleter that the pointer may own. Here is the declaration from cppreference::unique_ptr and cppreference::shared_ptr:



template<
class T,
class Deleter = std::default_delete<T>
> class unique_ptr;

template< class T > class shared_ptr;


As you can see the unique_ptr "saves" the type of the the Deleter-object as a template argument. This can also be seen in the way the Deleter is retrieved from the pointer later on:



// unique_ptr has a member function to retrieve the Deleter
template<
class T,
class Deleter = std::default_delete<T>
>
Deleter& unique_ptr<T, Deleter>::get_deleter();

// For shared_ptr this is not a member function
template<class Deleter, class T>
Deleter* get_deleter(const std::shared_ptr<T>& p);


Can someone explain the rational behind this difference? I clearly favor the concept for unique_ptr why is this not applied to shared_ptr aswell? Also, why would get_deleter be a non-member function in the latter case?


Aucun commentaire:

Enregistrer un commentaire