Last active
December 4, 2025 19:06
-
-
Save vlaleli/a8e5ee832bfa737d0c0e2843c7c57051 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include "my_unique_ptr.h" | |
| #include "my_shared_ptr.h" | |
| using namespace std; | |
| int main() | |
| { | |
| cout << "=== TEST my_unique_ptr ===" << endl; | |
| { | |
| my_unique_ptr<int> u1(new int(10)); | |
| cout << "u1 value = " << *u1 << endl; | |
| my_unique_ptr<int> u2 = std::move(u1); | |
| cout << "u1 after move = " << u1.Get() << endl; | |
| cout << "u2 value = " << *u2 << endl; | |
| u2.Reset(); | |
| cout << "u2 after reset = " << u2.Get() << endl; | |
| } | |
| cout << "\n=== TEST my_shared_ptr ===" << endl; | |
| { | |
| my_shared_ptr<int> s1(new int(20)); | |
| cout << "s1 value = " << *s1 << endl; | |
| cout << "count = " << s1.UseCount() << endl; | |
| { | |
| my_shared_ptr<int> s2 = s1; | |
| cout << "s2 value = " << *s2 << endl; | |
| cout << "count after copy = " << s1.UseCount() << endl; | |
| my_shared_ptr<int> s3 = s2; | |
| cout << "count after another copy = " << s1.UseCount() << endl; | |
| } | |
| cout << "count after s2/s3 destroyed = " << s1.UseCount() << endl; | |
| } | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| template <class T> | |
| class my_unique_ptr | |
| { | |
| T* ptr; | |
| public: | |
| my_unique_ptr(T* p = nullptr) : ptr(p) {} | |
| my_unique_ptr(const my_unique_ptr& other) = delete; | |
| my_unique_ptr& operator=(const my_unique_ptr& other) = delete; | |
| my_unique_ptr(my_unique_ptr&& other) | |
| { | |
| ptr = other.ptr; | |
| other.ptr = nullptr; | |
| } | |
| my_unique_ptr& operator=(my_unique_ptr&& other) | |
| { | |
| if (this != &other) | |
| { | |
| delete ptr; | |
| ptr = other.ptr; | |
| other.ptr = nullptr; | |
| } | |
| return *this; | |
| } | |
| ~my_unique_ptr() | |
| { | |
| delete ptr; | |
| } | |
| T* Get() const | |
| { | |
| return ptr; | |
| } | |
| void Reset() | |
| { | |
| delete ptr; | |
| ptr = nullptr; | |
| } | |
| T& operator*() const | |
| { | |
| return *ptr; | |
| } | |
| T* operator->() const | |
| { | |
| return ptr; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment