智能指针
https://www.cnblogs.com/linuxAndMcu/p/10409723.html
智能指针的实现:https://www.cnblogs.com/wxquare/p/4759020.html
从较浅的层面看,智能指针是利用了一种叫做RAII(资源获取即初始化)的技术对普通的指针进行封装,这使得智能指针实质是一个对象,行为表现的却像一个指针。
#include<iostream>
#include<vector>
#include<string>
#include <unordered_map>
#include<memory>
using namespace std;
template<typename T>
class SmartPointer {
private :
T* _ptr;
size_t* count;
public:
SmartPointer(T* ptr = nullptr) : _ptr(ptr){
if (_ptr) {
count = new size_t(1);
}
else {
count = new size_t(0);
}
}
SmartPointer(const SmartPointer& ptr) {
if (this != &ptr) {
this->_ptr = ptr._ptr;
this->count = ptr.count;
(*this->count)++;
}
}
SmartPointer& operator=(const SmartPointer& ptr) {
if (this->_ptr == ptr._ptr) {
return *this;
}
if (this->_ptr) {
(*this->count)--;
if (this->count == 0) {
delete this->_ptr;
delete this->count;
}
}
this->_ptr = ptr._ptr;
this->count = ptr.count;
(*this->count)++;
return *this;
}
T& operator*() {
assert(this->_ptr == nullptr);
return *(this->_ptr);
}
T& operator->() {
assert(this->_ptr == nullptr);
return this->_ptr;
}
~SmartPointer() {
(*this->count)--;
if (*this->count == 0) {
delete this->_ptr;
delete this->count;
}
}
size_t use_count() {
return *this->count;
}
};
int main() {
SmartPointer<int> sp(new int(10));
SmartPointer<int> sp2(sp);
SmartPointer<int> sp3(new int(20));
sp2 = sp3;
std::cout << sp.use_count() << std::endl;
std::cout << sp3.use_count() << std::endl;
}
weak_ptr如何解决相互引用的问题
看参考文章第一篇