Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using namespace std;
- template <typename T>
- class SharedPtr {
- private:
- T * ptr = nullptr;
- int * counter = new int(1);
- public:
- SharedPtr() {
- *counter = 1;
- }
- SharedPtr(T* input) {
- *counter = 1;
- ptr = input;
- }
- SharedPtr(const SharedPtr& input) {
- counter = input.counter;
- *counter += 1;
- ptr = input.ptr;
- }
- SharedPtr(SharedPtr&& other) noexcept {
- ptr = other.ptr;
- other.ptr = nullptr;
- counter = other.counter;
- *counter += 1;
- }
- SharedPtr operator=(T * input) noexcept {
- *counter -= 1;
- if (!(*counter)) {
- delete ptr;
- }
- ptr = input;
- counter = new int(1);
- return *this;
- }
- SharedPtr& operator =(const SharedPtr<T>& other) noexcept {
- *counter -= 1;
- if (!(*counter)) {
- delete ptr;
- }
- ptr = other.ptr;
- counter = other.counter;
- *counter += 1;
- return *this;
- }
- SharedPtr& operator =(SharedPtr<T>&& other) noexcept {
- *counter -= 1;
- if (!(*counter)) {
- delete ptr;
- }
- ptr = other.ptr;
- counter = other.counter;
- *counter += 1;
- return *this;
- }
- T* operator ->() const noexcept {
- return ptr;
- }
- T& operator*() const noexcept {
- return *ptr;
- }
- T& operator*() noexcept {
- return *ptr;
- }
- void reset(T* t) {
- --(*counter);
- if (!(*counter)) {
- delete ptr;
- }
- ptr = t;
- counter = new int(1);
- }
- void swap(SharedPtr<T>& other) noexcept {
- std::swap(ptr, other.ptr);
- std::swap(counter, other.counter);
- }
- T* get() const noexcept {
- return ptr;
- }
- explicit operator bool() const {
- if (ptr) {
- return true;
- }
- return false;
- }
- ~SharedPtr() {
- --(*counter);
- if (!(*counter)) {
- delete ptr;
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement