c++智能指针的实现 my smart_pointer

        想写个智能指针,以加深理解。在网上搜了好多例子,都不是很满意,有的都编不过。参考网上的代码,自己改写了一个版本。

设计思路

如何实现智能指针?
    首先要明确,智能指针有哪些基本的功能?
    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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值