智能指针 share_ptr的是面试中经常问到的问题, 结合weak_ptr 去一起优化share_ptr 检测当中count的数量的变化
简易实现, 直接上代码
/*
* @Author: your name
* @Date: 2021-09-06 16:34:18
* @LastEditTime: 2021-10-12 00:54:28
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /practice/practice/5.cpp
*/
/*************************************************************************
> File Name: 5.cpp
> Author: zhangfb
> Mail: 1819067326@qq.com
> Created Time: 四 9/ 2 18:36:13 2021
************************************************************************/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <stack>
#include <queue>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
class shared_count {
public:
shared_count() : count_(1) {}
void add_count() {
++count_;
}
long redues_count() {
return --count_;
}
long get_count() {
return count_;
}
private:
long count_;
};
template <typename T>
class smart_ptr {
private:
T *ptr_;
shared_count* shared_count_;
public:
template<typename U>
friend class smart_ptr;
explicit smart_ptr(T *ptr = nullptr)
: ptr_(ptr) {
if (ptr) {
shared_count_ = new shared_count();
}
}
~smart_ptr() {
if (ptr_ && !shared_count_->redues_count()) {
delete ptr_;
delete shared_count_;
}
}
//左值
template<typename U>
smart_ptr(const smart_ptr<U>& other) {
ptr_ = other.ptr_;
if (ptr_) {
other.shared_count_->add_count();
shared_count_ = other.shared_count_;
}
}
//右值
template<typename U>
smart_ptr(smart_ptr<U>&& other) {
ptr_ = other.ptr_;
if(ptr_) {
shared_count_ = other.shared_count_;
other.ptr_ = nullptr;
}
}
smart_ptr& operator=(smart_ptr rhs) {
rhs.swap(*this);
return *this;
}
void swap(smart_ptr& rhs) {
std::swap(ptr_, rhs.ptr_);
std::swap(shared_count_, rhs.shared_count_);
}
T *get() const {
return ptr_;
}
long use_count() const{
if (ptr_) {
return shared_count_->get_count();
} else {
return 0;
}
}
T& operator*() const {
return *ptr_;
}
T *operator->() const {
return ptr_;
}
operator bool() const {
return ptr_;
}
};
class shape {
public:
virtual ~shape() {}
};
class circle : public shape {
public:
~circle() {cout << "~circle()" << endl;}
};
int main() {
smart_ptr<circle> ptr1(new circle());
cout << "ptr1 use count " << ptr1.use_count() << endl;
smart_ptr<shape> ptr2;
cout << "ptr2 use count " << ptr2.use_count() << endl;
ptr2 = ptr1;
cout << "ptr2 use count " << ptr2.use_count() << endl;
return 0;
}
实现起来只要是经常使用c++面向对象编程的那实现起来是比较简单的, 不足欢迎大家进行指正