File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < memory>
2+ #include < utility> // std::exchange
3+
4+ template <typename T, typename Deleter = std::default_delete<T>>
5+ class unique_ptr {
6+ private:
7+ T* ptr;
8+ Deleter deleter;
9+
10+ public:
11+ // Constructors
12+ explicit unique_ptr (T* p = nullptr ) noexcept
13+ : ptr(p) {}
14+
15+ // Destructor
16+ ~unique_ptr () {
17+ if (ptr) {
18+ deleter (ptr);
19+ }
20+ }
21+
22+ // Delete copy semantics
23+ unique_ptr (const unique_ptr&) = delete ;
24+ unique_ptr& operator =(const unique_ptr&) = delete ;
25+
26+ // Move constructor
27+ unique_ptr (unique_ptr&& other) noexcept
28+ : ptr(std::exchange(other.ptr, nullptr )) {}
29+
30+ // Move assignment
31+ unique_ptr& operator =(unique_ptr&& other) noexcept {
32+ if (this != &other) {
33+ delete ptr; // clean up current resource
34+ ptr = std::exchange (other.ptr , nullptr );
35+ }
36+ return *this ;
37+ }
38+
39+ // Observers
40+ T* get () const noexcept { return ptr; }
41+
42+ T& operator *() const noexcept { return *ptr; }
43+
44+ T* operator ->() const noexcept { return ptr; }
45+
46+ explicit operator bool () const noexcept { return ptr != nullptr ; }
47+
48+ // Modifiers
49+ T* release () noexcept { return std::exchange (ptr, nullptr ); }
50+
51+ void reset (T* p = nullptr ) noexcept {
52+ delete ptr;
53+ ptr = p;
54+ }
55+ };
56+
57+ template <typename T, typename ... Args>
58+ unique_ptr<T> make_unique (Args&&... args) {
59+ return unique_ptr<T>(new T (std::forward<Args>(args)...));
60+ }
You can’t perform that action at this time.
0 commit comments