unique_ptr伪代码
template<typename T, typename Deleter = DefaultDelete<T>>
class Unique_ptr
{
private:
T* ptr;
Deleter deleter;
public:
Unique_ptr(T* ptr,Deleter deleteter=Deleter()) : ptr(ptr), deleter(deleteter) {}
~Unique_ptr() {
if (ptr)
deleter(ptr);
};
Unique_ptr(Unique_ptr& other)=delete;
Unique_ptr& operator=(Unique_ptr& other)=delete;
Unique_ptr(Unique_ptr&& other) {
if (ptr)
deleter(ptr);
ptr = other.ptr;
deleter =std::move(other.deleter);
other.ptr = nullptr;
}
Unique_ptr& operator=(Unique_ptr&& other) {
if (this == &other)
return *this;
if (ptr)
deleter(ptr);
ptr = other.ptr;
deleter =std::move(other.deleter);
other.ptr = nullptr;
return *this;
}
T* get() { return ptr; }
void reset(T* ptr = nullptr) {
if (this->ptr)
deleter(this->ptr);
this->ptr = ptr;
}
T& operator*() { return *ptr; }
T* operator->() { return ptr; }
};
template<typename T>
class DefaultDelete {
public:
DefaultDelete() = default;
void operator()(T* ptr) const {
delete ptr;
}
};
通过上诉伪代码可知,unique_ptr独占所有权,不能复制,只能移动
Share_ptr伪代码
#include <functional>
template<typename T>
class Share_ptr
{
public:
Share_ptr(T* ptr, std::function<void(void*)> deleter)
{
m_ptr = ptr;
m_block = new Block(ptr, deleter);
}
~Share_ptr()
{
if (m_block->m_count == 0)
{
m_block->deleter(m_ptr);
delete m_block;
}
}
Share_ptr(const Share_ptr& other) {
m_ptr=other.m_ptr;
m_block=other.m_block;
if(m_block) m_block->increase_ref();
}
Share_ptr& operator=(const Share_ptr& other) {
if (this!=other) {
if (m_block) {
if (m_block->decrease_ref()==0) {
m_block->deleter(m_ptr);
delete m_block;
}
}
m_ptr = other.m_ptr;
m_block = other.m_block;
if (m_block)m_block->increase_ref();
}
return *this;
}
Share_ptr(Share_ptr&& other) {
m_ptr = other.m_ptr;
m_block = other.m_block;
other.m_ptr = nullptr;
other.m_block = nullptr;
}
Share_ptr& operator=(Share_ptr&& other) {
if (this != other) {
if (m_block) {
if (m_block->decrease_ref() == 0) {
m_block->deleter(m_ptr);
delete m_block;
}
}
m_ptr = other.m_ptr;
m_block = other.m_block;
other.m_ptr = nullptr;
other.m_block = nullptr;
}
return *this;
}
T* get()
{
return m_ptr;
}
T& operator*()
{
return *m_ptr;
}
T* operator->()
{
return m_ptr;
}
private:
T* m_ptr;
Block* m_block;
};
struct Block
{
int m_count;
std::function<void(void*)> deleter;
Block(void* p, std::function<void(void*)> d) : m_count(0), deleter(d) {};
void increase_ref()
{
m_count++;
}
void decrease_ref()
{
m_count--;
}
};
share_ptr共享所有权,内部有共享控制块(指向同一个堆内存)维护引用计数,最后一个引用销毁的时释放资源。