kakoune

Fork of kakoune, an acceptable text editor
git clone git://git.laack.co/kakoune.git
Log | Files | Refs

unique_ptr.hh (1837B)


      1 #ifndef unique_ptr_hh_INCLUDED
      2 #define unique_ptr_hh_INCLUDED
      3 
      4 #include <utility>
      5 #include <type_traits>
      6 #include <cstddef>
      7 
      8 namespace Kakoune
      9 {
     10 
     11 template<typename T>
     12 class UniquePtr
     13 {
     14     using Type = std::remove_extent_t<T>;
     15 
     16 public:
     17     explicit UniquePtr(Type* ptr = nullptr) : m_ptr{ptr} {}
     18     UniquePtr(std::nullptr_t) : m_ptr{nullptr} {}
     19 
     20     UniquePtr(const UniquePtr&) = delete;
     21     UniquePtr& operator=(const UniquePtr&) = delete;
     22 
     23     template<typename U> requires std::is_convertible_v<U*, T*>
     24     UniquePtr(UniquePtr<U>&& other) noexcept { m_ptr = other.release(); }
     25 
     26     template<typename U> requires std::is_convertible_v<U*, T*>
     27     UniquePtr& operator=(UniquePtr<U>&& other) noexcept(noexcept(std::declval<Type>().~Type()))
     28     {
     29         destroy();
     30         m_ptr = other.release();
     31         return *this;
     32     }
     33     ~UniquePtr() { destroy(); }
     34 
     35     Type* get() const { return m_ptr; }
     36     Type* operator->() const { return m_ptr; };
     37     Type& operator*() const { return *m_ptr; };
     38     Type& operator[](size_t i) const requires std::is_array_v<T> { return m_ptr[i]; }
     39     Type* release() { auto ptr = m_ptr; m_ptr = nullptr; return ptr; }
     40 
     41     void reset(Type* ptr = nullptr) { destroy(); m_ptr = ptr; }
     42 
     43     explicit operator bool() const { return m_ptr != nullptr; }
     44 
     45     friend bool operator==(const UniquePtr&, const UniquePtr&) = default;
     46     friend bool operator==(const UniquePtr& lhs, const Type* rhs) { return lhs.get() == rhs; }
     47 
     48 private:
     49     void destroy()
     50     {
     51         if constexpr (std::is_array_v<T>)
     52             delete[] m_ptr;
     53         else
     54             delete m_ptr;
     55         m_ptr = nullptr;
     56     }
     57 
     58     Type* m_ptr;
     59 };
     60 
     61 template<typename T, typename... Args>
     62 UniquePtr<T> make_unique_ptr(Args&&... args)
     63 {
     64     return UniquePtr<T>(new T(std::forward<Args>(args)...));
     65 }
     66 
     67 }
     68 
     69 #endif // unique_ptr_hh_INCLUDED