1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| unique-onwership smart pointer ? 只能一个对象拥有资源 ? 转让所有权 ? move-sematics ? 避免拷贝 ?
使用时智能指针是个栈对象,里面包了一个指针,对象在出作用域的时候会析构,然后析构里面对我们包裹的指针进行释放
#pragma once #include <memory>
namespace hinata {
template <typename T, typename D> class unique_ptr : public std::_Unique_ptr_base<T, D> { public: typedef unique_ptr<T, D> Myt_; typedef _Unique_ptr_base<T, D> Mybase_; typedef typename Mybase_::pointer pointer_; typedef T element_type_; typedef D deleter_type_;
using Mybase_::get_deleter;
constexpr unique_ptr() noexcept : Mybase_(pointer_()) { static_assert(!is_pointer<D>::value, "unique_ptr constructed with null deleter pointer") }
explicit unique_ptr(pointer_ p) noexcept : Mybase_(pointer_()) { static_assert(!is_pointer<D>::value, "unique_ptr constructed with null deleter pointer") }
unique_ptr(unique_ptr&& right) _NOEXCEPT : Mybase_(right.release(), ::std::forward<_Dx>(right.get_deleter())) { }
~unique_ptr() noexcept { if (get() != pointer_()) this->get_deleter()(get()); }
Myt_& operator=(nullptr_t) { reset(); return (*this); }
pointer_ operator->() const noexcept { return pointer_(); }
pointer_ get() const noexcept { return (this->_Myptr()); }
explicit operator bool() const noexcept { return (get() != pointer()); }
pointer_ release() noexcept { pointer_ ans = get(); this->_Myptr() = pointer(); return (ans); }
void reset(pointer_ ptr = pointer_()) noexcept { pointer old = get(); this->_Myptr() = ptr; if (old != pointer_()) this->get_deleter()(old); }
unique_ptr(const unique_ptr&) = delete; unique_ptr& operator=(const unique_ptr&) = delete;
private:
};
template <class T1, class D1, class T2, class D2> bool operator==(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y) { return false; } }
|