Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<class T>
- struct SharedPtr
- {
- template<class P>
- struct Wrapper
- {
- P* ptr;
- long count;
- Wrapper(P* ptr) : ptr(ptr), count(1)
- { if (ptr == nullptr ) throw "Invalid pointer"; }
- ~Wrapper() { delete ptr; }
- void addRef() { ++count; }
- void release()
- {
- if (--count == 0)
- {
- delete this;
- }
- }
- };
- explicit SharedPtr(T *ptr = nullptr)
- : holder(ptr ? new Wrapper<T>(ptr) : nullptr)
- {
- }
- SharedPtr(const SharedPtr<T>& other) : holder(nullptr)
- {
- copy(other);
- }
- ~SharedPtr()
- {
- clear();
- }
- SharedPtr& operator=(const SharedPtr<T>& other)
- {
- if (this != &other)
- {
- copy(other);
- }
- return *this;
- }
- T* get() const { return holder ? holder->ptr : nullptr;}
- void reset(T *ptr = nullptr)
- {
- clear();
- if (ptr != nullptr)
- {
- holder = new Wrapper<T>(ptr);
- }
- }
- const T& operator*() const
- {
- if (holder == nullptr) throw "Invalid pointer";
- return *holder->ptr;
- }
- T& operator*()
- {
- if (holder == nullptr) throw "Invalid pointer";
- return *holder->ptr;
- }
- T* operator->() const
- {
- return get();
- }
- private:
- void copy(const SharedPtr<T>& other)
- {
- clear();
- if (other.holder)
- {
- holder = other.holder;
- holder->addRef();
- }
- }
- void clear()
- {
- if (holder)
- {
- holder->release();
- holder = nullptr;
- }
- }
- Wrapper<T> *holder;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement