想写个智能指针,以加深理解。在网上搜了好多例子,都不是很满意,有的都编不过。参考网上的代码,自己改写了一个版本。
设计思路
如何实现智能指针?
首先要明确,智能指针有哪些基本的功能?
1.管理引用计数,并当引用计数为0时,自动析构。
2.具备一个指针最基本的功能,需要重载以下操作符:
operator*()
operator->()
3.需要定义以下几个函数
construct
copy construct
assign construct
~construct
如何实现呢?
1.确定成员变量
T* m_ptr,用来管理指向的对象
m_refCount_ptr,用来管理引用计数
测试case
1.构造函数
2.copy construct
3.assign construct
4.自动析构
存在的不足:
功能不全面,有的地方写的不是很规范,没考虑多线程的情况。
#include <stdio.h>
template<typename T>
class SmartPtr {
public:
SmartPtr(T* ptr = nullptr): m_ptr(ptr)
{
printf("construct\n");
if (m_ptr) {
m_refCount_ptr = new UseCount();
}
}
SmartPtr(const SmartPtr& ptr) {
printf("copy construct\n");
m_ptr = ptr.m_ptr;
m_refCount_ptr = ptr.m_refCount_ptr;
m_refCount_ptr->AddCount();
}
SmartPtr& operator=(const SmartPtr& ptr) {
printf("assign construct\n");
if (this == &ptr) {
return *this;
}
m_ptr = ptr.m_ptr;
m_refCount_ptr = ptr.m_refCount_ptr;
m_refCount_ptr->AddCount();
return *this;
}
~SmartPtr() {
m_refCount_ptr->ReduceCount();
printf("~construct,rest GetUseCount:%ld\n", m_refCount_ptr->GetUseCount());
if ((m_ptr) && (0 == m_refCount_ptr->GetUseCount())) {
delete m_ptr;
delete m_refCount_ptr;
}
}
long GetUseCount() { return m_refCount_ptr->GetUseCount(); }
T operator*() { return *m_ptr; }
T* operator->() { return m_ptr; }
private:
class UseCount {
public:
UseCount(): m_count(1) {}
~UseCount() = default;
void AddCount() { m_count++; }
void ReduceCount() { m_count--; }
long GetUseCount() { return m_count; }
private:
long m_count;
};
private:
T* m_ptr;
UseCount* m_refCount_ptr;
};
class Test {
public:
Test() { printf("Test()\n"); }
~Test() { printf("~Test()\n"); }
};
int main()
{
SmartPtr<Test> ptr1(new Test());
printf("UseCount:%ld\n", ptr1.GetUseCount());
SmartPtr<Test> ptr2 = ptr1;
printf("UseCount:%ld\n", ptr1.GetUseCount());
SmartPtr<Test> ptr3;
ptr3 = ptr2;
printf("UseCount:%ld\n", ptr1.GetUseCount());
return 0;
}