aboutsummaryrefslogtreecommitdiff
path: root/include/cru/ui/DeleteLater.h
blob: 0f04c73a3350f36248b4201379278b0c22e76b27 (plain)
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
#pragma once
#include "Base.h"

#include <memory>
#include <utility>

namespace cru::ui {
class CRU_UI_API DeleteLaterImpl {
 public:
  virtual ~DeleteLaterImpl();
  void DeleteLater();

 protected:
  virtual void OnPrepareDelete();
};

template <typename T>
class DeleteLaterPtr {
 public:
  DeleteLaterPtr() = default;

  DeleteLaterPtr(const DeleteLaterPtr& other) = delete;
  DeleteLaterPtr& operator=(const DeleteLaterPtr& other) = delete;

  DeleteLaterPtr(DeleteLaterPtr&& other) noexcept : ptr_(other.ptr_) {
    other.ptr_ = nullptr;
  }

  DeleteLaterPtr& operator=(DeleteLaterPtr&& other) noexcept {
    if (this != &other) {
      if (ptr_ != nullptr) {
        ptr_->DeleteLater();
      }

      ptr_ = other.ptr_;
      other.ptr_ = nullptr;
    }
    return *this;
  }

  ~DeleteLaterPtr() {
    if (ptr_ != nullptr) {
      ptr_->DeleteLater();
    }
  }

  explicit DeleteLaterPtr(T* ptr) : ptr_(ptr) {}
  DeleteLaterPtr(std::unique_ptr<T>&& ptr) : ptr_(ptr.release()) {}

  T& operator*() const { return *ptr_; }
  T* operator->() const { return ptr_; }

  explicit operator bool() const { return ptr_ != nullptr; }

  T* get() const { return ptr_; }

 private:
  T* ptr_ = nullptr;
};

template <typename T, typename... Args>
DeleteLaterPtr<T> MakeDeleteLaterPtr(Args&&... args) {
  return DeleteLaterPtr<T>(new T(std::forward<Args>(args)...));
}
}  // namespace cru::ui