template<typename T>
class shared_ptr {
public:
shared_ptr() : ptr(nullptr), count(nullptr) {}
explicit shared_ptr(T* p) : ptr(p), count(new size_t(1)) {}
shared_ptr(const shared_ptr& other) {
ptr = other.ptr;
count = other.count;
++*count;
}
shared_ptr& operator=(const shared_ptr& other) {
if (this == &other)
return *this;
release();
ptr = other.ptr;
count = other.count;
++*count;
return *this;
}
~shared_ptr() {
release();
}
T& operator*() const {
return *ptr;
}
T* operator->() const {
return ptr;
}
size_t use_count() const {
return count ? *count : 0;
}
T* get() const {
return ptr;
}
void reset() {
release();
}
void reset(T* p) {
release();
ptr = p;
count = new size_t(1);
}
private:
void release() {
if (count && --*count == 0) {
delete count;
delete ptr;
count = nullptr;
ptr = nullptr;
}
}
T* ptr;
size_t* count;
};
面试手搓高频考点之智能指针shared_ptr
最新推荐文章于 2024-06-01 18:28:10 发布