Skip to content

Instantly share code, notes, and snippets.

@l-bat
Created October 24, 2017 16:42
Show Gist options
  • Save l-bat/f68a1176df8d89a73396c1adaeb091d6 to your computer and use it in GitHub Desktop.
Save l-bat/f68a1176df8d89a73396c1adaeb091d6 to your computer and use it in GitHub Desktop.
smart_pointers
#include <iostream>
template <class T>
class my_unique_ptr
{
private:
T* ptr;
public:
my_unique_ptr() : ptr(nullptr) {};
my_unique_ptr( const my_unique_ptr& ) = delete;
my_unique_ptr& operator=( const my_unique_ptr& ) = delete;
my_unique_ptr (my_unique_ptr&& temp) noexcept {
ptr = temp.ptr;
temp.ptr = nullptr;
}
explicit my_unique_ptr(T* _ptr) : ptr(_ptr) {};
T* getPtr() const { return ptr; }
T& operator*() { return *ptr; }
void setPtr(T *ptr) {
my_unique_ptr::ptr = ptr;
}
virtual ~my_unique_ptr()
{
if (ptr != nullptr)
delete ptr;
}
};
template <class T>
class Block
{
private:
T* ptr;
int shared_count;
int weak_count;
public:
Block(T* p) : ptr(p), shared_count(1), weak_count(1) {}
void setPtr(T *ptr) {
Block::ptr = ptr;
}
int getShared_count() const {
return shared_count;
}
int decShared_count() {
return shared_count--;
}
int incShared_count() {
return shared_count++;
}
int incWeak_count() {
return weak_count++;
}
};
template <class T>
class my_shared_ptr {
private:
T *ptr;
Block<T> *unit;
public:
my_shared_ptr() : ptr(nullptr), unit(nullptr) {}
explicit my_shared_ptr(my_unique_ptr&& temp) : ptr(temp.()), unit(temp.()) {
temp.setPtr(nullptr);
}
explicit my_shared_ptr(T *p) : ptr(p), unit(p) {}
my_shared_ptr(const my_shared_ptr &temp) : ptr(temp.getPtr()), unit(temp.getPtr()) {
unit->incShared_count();
}
my_shared_ptr& operator=(const my_shared_ptr &temp) {
if(&temp == this)
return *this;
ptr = temp.ptr;
unit = temp.unit;
unit->incShared_count();
return *this;
}
my_shared_ptr(my_shared_ptr &&temp) noexcept : ptr(temp.ptr), unit(temp.ptr) {
temp.ptr = nullptr;
temp.unit->setPtr(nullptr);
}
my_shared_ptr& operator=(my_unique_ptr&& temp) noexcept {
ptr = temp.getPtr();
unit = new Block<T>(temp.getPtr());
temp.setPtr(nullptr);
return *this;
}
T* getPtr() const { return ptr; }
~my_shared_ptr() {
if (unit->getShared_count() == 0) {
delete ptr;
delete unit;
} else
unit->decShared_count();
}
};
template <class T>
class my_weak_ptr
{
T* ptr;
Block *unit;
public:
my_weak_ptr() : ptr(nullptr), unit(nullptr) {}
my_weak_ptr(const my_shared_ptr& temp) : ptr(temp.getPtr()), unit(temp.getPtr()) {
unit->incWeak_count();
}
my_weak_ptr(const my_weak_ptr& temp) : ptr(temp.ptr), unit(temp.ptr){
unit->incWeak_count();
}
T& operator*() { return *ptr; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment