Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template <typename T>
- class ptr {
- size_t c;
- public:
- T* p;
- size_t* refcount;
- ptr() {
- c = 0;
- refcount = &c;
- *refcount = 0;
- p = new T[1];
- }
- ptr(ptr& other) {
- copy(other);
- }
- ptr& operator =(ptr& other) {
- this->copy(other);
- return *this;
- }
- ~ptr() {
- delete p;
- }
- T& operator*() {
- return *p;
- }
- private:
- void copy(ptr& other) {
- p = other.p;
- refcount = other.refcount;
- c = other.c;
- }
- ptr& copy() {
- return ptr(this);
- }
- };
- template<typename T>
- class ptr_unique {
- ptr<T> p;
- public:
- ptr_unique():p() {}
- ptr_unique(ptr_unique& other) = delete;
- T& operator*() {
- return *p;
- }
- void operator=(T& val) {
- *p = val;
- }
- };
- template<typename T>
- class ptr_shared {
- public:
- ptr<T> p;
- ptr_shared() :p() {
- (*p.refcount)++;
- }
- ptr_shared(ptr_shared& other) {
- copy(other);
- }
- ~ptr_shared() {
- (*p.refcount)--;
- if (*p.refcount) {
- p.p = nullptr;
- }
- }
- ptr_shared& operator=(ptr_shared& other) {
- this->copy(other);
- return *this;
- }
- T& operator*(){
- return *p;
- }
- private:
- void copy(ptr_shared& other) {
- this->p = other.p;
- (*p.refcount)++;
- }
- ptr_shared& copy() {
- (*p.refcount)++;
- return ptr_shared(this);
- }
- };
- template<typename T>
- class ptr_weak {
- ptr<T> p;
- public:
- ptr_weak() :p(){}
- ptr_weak(ptr_weak& other) {
- copy(other);
- }
- ptr_weak(ptr_shared<T>& shared) {
- copy(shared);
- }
- ~ptr_weak() {
- p.p = nullptr;
- }
- T& operator*() {
- return *p;
- }
- ptr_weak& operator=(ptr_weak& other) {
- this->copy(other);
- return *this;
- }
- ptr_weak& operator=(ptr_shared<T>& shared) {
- this->copy(shared);
- return *this;
- }
- ptr_shared<T>& make_shared() {
- (*p.refcount)++;
- return (ptr_shared<T>&)*this;
- }
- void make_shared(ptr_weak& weak) {
- *this = weak.make_shared();
- }
- bool still_alive() {
- if (*p.refcount) { return true; }
- return false;
- }
- private:
- void copy(ptr_shared<T>& other) {
- p = other.p;
- }
- void copy(ptr_weak& other) {
- p = other.p;
- }
- ptr_weak& copy() {
- return *this;
- }
- };
- int main() {
- //ptr_unique<int> a;
- ////ptr_unique<int>b = a; //errors as it should bc no copies
- //*a = 5;
- //cout << *a << "\n";
- ptr_weak<int> w;
- {
- ptr_shared<int> a;
- ptr_shared<int> b = a;
- w = b;
- ptr_shared<int> c = a;
- *a = 8;
- }
- if (w.still_alive()) {
- cout << *w;
- }
- else { cout << "dead"; }
- }
Add Comment
Please, Sign In to add comment