1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| template<typename T> class SharedPtr { private: T* ptr_; int* count_; std::mutex* mutex_; void release() { bool should_delete = false; { std::lock_guard<std::mutex> lock(*mutex_); if (--(*count_) == 0) { should_delete = true; } } if (should_delete) { delete ptr_; delete count_; delete mutex_; } }
public: explicit SharedPtr(T* ptr = nullptr) : ptr_(ptr), count_(new int(1)), mutex_(new std::mutex) {} SharedPtr(const SharedPtr& other) : ptr_(other.ptr_), count_(other.count_), mutex_(other.mutex_) { std::lock_guard<std::mutex> lock(*mutex_); ++(*count_); } SharedPtr& operator=(const SharedPtr& other) { if (this != &other) { release(); ptr_ = other.ptr_; count_ = other.count_; mutex_ = other.mutex_; std::lock_guard<std::mutex> lock(*mutex_); ++(*count_); } return *this; } SharedPtr(SharedPtr&& other) noexcept : ptr_(other.ptr_), count_(other.count_), mutex_(other.mutex_) { other.ptr_ = nullptr; other.count_ = nullptr; other.mutex_ = nullptr; } ~SharedPtr() { release(); } T& operator*() { return *ptr_; } T* operator->() { return ptr_; } T* get() { return ptr_; } int use_count() { return count_ ? *count_ : 0; } };
|