Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template <typename T, typename Deleter = Slug<T>>
- class UniquePtr {
- public:
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Constructors
- explicit UniquePtr(T* ptr = nullptr) : comp_pair(ptr, Deleter()) {
- }
- template <typename Del>
- UniquePtr(T* ptr, Del&& deleter) : comp_pair(ptr, std::forward<Del>(deleter)) {
- }
- UniquePtr(UniquePtr&& other) noexcept :comp_pair(nullptr,Deleter()){
- comp_pair.GetFirst() = other.comp_pair.GetFirst();
- other.comp_pair.GetFirst() = nullptr;
- }
- template <typename T1>
- UniquePtr(UniquePtr<T1>&& other) noexcept :comp_pair(nullptr,Deleter()){
- comp_pair.GetFirst() = other.comp_pair.GetFirst();
- other.Release();
- }
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // `operator=`-s
- UniquePtr& operator=(UniquePtr&& other) noexcept {
- if (comp_pair.GetFirst() == other.comp_pair.GetFirst()) {
- return *this;
- }
- comp_pair.GetFirst() = other.comp_pair.GetFirst();
- comp_pair.GetSecond() = std::forward<Deleter>(other.comp_pair.GetSecond());
- Reset(other.Release());
- return *this;
- }
- UniquePtr& operator=(std::nullptr_t) noexcept {
- Reset();
- return *this;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Destructor
- ~UniquePtr() {
- comp_pair.GetSecond()(comp_pair.GetFirst());
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Modifiers
- T* Release() {
- T* result = nullptr;
- std::swap(result, comp_pair.GetFirst());
- return result;
- }
- void Reset(T* ptr = nullptr) {
- T* old_p = comp_pair.GetFirst();
- comp_pair.GetFirst() = ptr;
- if (old_p) {
- comp_pair.GetSecond()(old_p);
- }
- }
- void Swap(UniquePtr& other) noexcept {
- std::swap(comp_pair.GetFirst(), other.comp_pair.GetFirst());
- std::swap(comp_pair.GetSecond(), other.comp_pair.GetSecond());
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Observers
- T* Get() const {
- return comp_pair.GetFirst();
- }
- T* Get() {
- return comp_pair.GetFirst();
- }
- Deleter& GetDeleter() {
- return comp_pair.GetSecond();
- }
- const Deleter& GetDeleter() const {
- return comp_pair.GetSecond();
- }
- explicit operator bool() const {
- return comp_pair.GetFirst();
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Single-object dereference operators
- std::add_lvalue_reference_t<T> operator*() const {
- return *comp_pair.GetFirst();
- }
- T* operator->() const {
- return comp_pair.GetFirst();
- }
- private:
- CompressedPair<T, Deleter> comp_pair;
- // T* ptr_;
- // Deleter deleter_;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement