1

I'm trying to understand how unique_ptr works inside. I found a simple implementation. Please tell me what the constructor does.

template<typename T, typename D = default_delete<T>>
class unique_ptr {
public:
    using pointer = T*;
    using element_type = T;
    using deleter_type = D;
 
unique_ptr(pointer p, 
        typename std::conditional<std::is_reference<deleter_type>::value,
            deleter_type, const deleter_type&>::type d) noexcept
    : _impl{p, d}
    { }
 
private:
    detail::Ptr<T, D> _impl;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
JDbP
  • 53
  • 4
  • _"Please tell me what the constructor does."_ - I have a potentially better idea: why don't you tell us which parts of the constructor you're having trouble understanding...? – Dai Nov 10 '22 at 05:41
  • Why is used typename std::conditional::value, deleter_type? Why can't I use explicit unique_ptr(T* raw_resource)? – JDbP Nov 10 '22 at 05:45
  • The constructor isn't really doing that many things. Are you asking what the `std::conditional` business in the parameter list, what's happening with the initialization of `_impl` in the member initializer list, or both? – Nathan Pierson Nov 10 '22 at 05:45
  • I don't understand the meaning of this expression. Why is this? typename std::conditional::value, deleter_type, const deleter_type&>::type d) – JDbP Nov 10 '22 at 05:47
  • [std::conditional](https://en.cppreference.com/w/cpp/types/conditional) is a struct whose member type `type` is defined based on whether `Condition` is `true` or `false`. So, if `std::is_reference::value` is true, the type of the argument `d` is `deleter_type`. Otherwise, the type is `const deleter_type&`. – Nathan Pierson Nov 10 '22 at 05:56
  • Perhaps you want to look at `make_unique()` to understand it better. – Thomas Weller Nov 10 '22 at 06:24
  • I understand what std::conditional does. I don't understand why this is needed. – JDbP Nov 10 '22 at 06:31
  • It is needed because [the specification of `std::unique_ptr`](https://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr) say it must be so. – j6t Nov 10 '22 at 07:10

0 Answers0