#include <iostream>
#include <memory>
#include <mutex>
template<class T>
class Shared_Ptr {
public:
Shared_Ptr(T *ptr = nullptr) : _pPtr(ptr), _pRefCount(new T()), _pMutex(std::make_shared<std::mutex>()) {}
~Shared_Ptr() {
std::cout << "~Shared_Ptr" << std::endl;
Release();
}
Shared_Ptr(const Shared_Ptr<T> &sp) : _pPtr(sp._pPtr), _pRefCount(sp._pRefCount), _pMutex(sp._pMutex) {
AddRefCount();
}
Shared_Ptr<T> &operator=(const Shared_Ptr<T> &sp) {
if (this != &sp) {
Release();
swap(*this, sp);
AddRefCount();
}
return *this;
}
Shared_Ptr(Shared_Ptr<T> &&sp) noexcept {
swap(*this, sp);
sp._pPtr = nullptr;
sp._pRefCount = nullptr;
}
Shared_Ptr<T> &operator=(Shared_Ptr<T> &&sp) noexcept {
swap(*this, sp);
sp._pPtr = nullptr;
sp._pRefCount = nullptr;
return *this;
}
T &operator*() {
return *_pPtr;
}
T *operator->() {
return _pPtr;
}
int useCount() const {
return _pRefCount ? *_pRefCount : 0;
}
T *get() const {
return _pPtr;
}
private:
void AddRefCount() {
if (_pRefCount)
{
std::lock_guard<std::mutex> lock(*_pMutex);
++(*_pRefCount);
}
}
void Release() {
if (_pRefCount)
{
std::lock_guard<std::mutex> lock(*_pMutex);
if (--(*_pRefCount) == 0) {
delete _pPtr;
delete _pRefCount;
}
}
}
friend void swap(Shared_Ptr<T> &lhs, Shared_Ptr<T> &rhs) noexcept {
using std::swap;
swap(lhs._pPtr, rhs._pPtr);
swap(lhs._pRefCount, rhs._pRefCount);
swap(lhs._pMutex, rhs._pMutex);
}
private:
int *_pRefCount;
T *_pPtr;
std::shared_ptr<std::mutex> _pMutex;
};
int main() {
Shared_Ptr<int> ptr(new int(42));
std::cout << "use count: " << ptr.useCount() << std::endl;
Shared_Ptr<int> ptr2 = std::move(ptr);
std::cout << "use count after move: " << ptr.useCount() << std::endl;
return 0;
}
06-30
1858
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-02
221
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-19
207
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-19
421
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交