Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<typename T>
- class MySharedPtr {
- private:
- size_t* n = nullptr;
- T* ptr = nullptr;
- public:
- void release() {
- if (n) {
- if (*n == 1) {
- delete n;
- delete ptr;
- } else {
- --*n;
- }
- }
- n = nullptr;
- ptr = nullptr;
- }
- MySharedPtr() = default;
- MySharedPtr(const MySharedPtr<T>& other) :
- ptr(other.ptr),
- n(other.n)
- {
- if (n) {
- ++*n;
- }
- }
- MySharedPtr(MySharedPtr<T>&& other) :
- ptr(other.ptr),
- n(other.n)
- {
- other.ptr = nullptr;
- other.n = nullptr;
- }
- MySharedPtr(T* new_ptr) :
- ptr(new_ptr),
- n(new size_t(1)) {
- }
- ~MySharedPtr() {
- release();
- }
- T& operator*() {
- return *ptr;
- }
- const T& operator*() const {
- return *ptr;
- }
- MySharedPtr<T>& operator= (const MySharedPtr<T>& other) {
- if (&other == this) {
- return *this;
- }
- release();
- n = other.n;
- ptr = other.ptr;
- if (n) {
- ++*n;
- }
- return *this;
- }
- MySharedPtr<T>& operator= (MySharedPtr<T>&& other) {
- if (&other == this) {
- return *this;
- }
- release();
- n = other.n;
- ptr = other.ptr;
- other.n = nullptr;
- other.ptr = nullptr;
- return *this;
- }
- };
- MySharedPtr<int> A(new int); // n = 1
- MySharedPtr<int> B(std::move(A)); //
- int& ref = *B;
- A = std::move(B);
- MySharedPtr<int> p(new int(10)); // n = 1
- MySharedPtr<int> a(p); // n = 2
- MySharedPtr<int> c(p); // n = 3
- MySharedPtr<int> p1(new int(9)); // n = 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement