C++ 手动实现简单的智能指针类

Willow ·
更新时间:2024-09-20
· 610 次阅读

何为智能指针,即不需要用户再自动手动New和Delete掉,由内部类进行new和delete,这样可以防止用户忘记释放掉指针而造成的内存泄漏。 这里简单的实现unique_ptr智能指针的方式。 头文件 // 自制智能指针类头文件 template class SmartPointer{ public: SmartPointer(T* ptr_); ~SmartPointer(); T* operator->() const; //重载->符号 T& operator*() const; //重载*符号 SmartPointer& operator=(SmartPointer&ptr_); //重写=符号::转移所有权 void Release(); //释放智能指针 T* GetObjPtr(); //得到指针地址 T * m_ptr; //存放智能指针 private: int m_count;//指针计数:为0时可释放 }; 实现文件 template SmartPointer::SmartPointer(T* ptr_) { // 判断是否为空 if (ptr_) { m_ptr = ptr_; m_count = 1; } else{ m_ptr = nullptr; cout << "指针为空,无法实现智能指针" << endl; m_count = 0; } } template SmartPointer::~SmartPointer() { if (m_ptr&&(m_count <= 1)) { cout << "---------析构-------" << endl; delete m_ptr; m_ptr = NULL; //置为空 } else { cout << "智能指针被转移:不进行析构" << endl; } } template T* SmartPointer::operator->() const { if (m_ptr) { return m_ptr; } else { cout << "智能指针为空,出错了!" << endl; return nullptr; } } template T& SmartPointer::operator*()const { if (m_ptr) { return *m_ptr; } else{ cout << "智能指针为空,出错了!" << endl; return NULL; } } template SmartPointer& SmartPointer::operator=(SmartPointer& ob_) { if (this != &ob_) { delete m_ptr; m_ptr = ob_.m_ptr; ob_.m_ptr = NULL; } return *this; } template void SmartPointer::Release() { if(m_ptr) { delete m_ptr; //提前释放 m_ptr = NULL; //需要置为空 m_count = 0; } } //得到指针对象 template T* SmartPointer::GetObjPtr() { if (m_ptr) { m_count ++; //计数增加 return m_ptr; } return nullptr; }

*使用方法如下:

//测试智能指针方法 void TestSmartPointer() { SmartPointer MM(new A()); SmartPointer FF(new A()); } int _tmain(int argc, _TCHAR* argv[]) { TestSmartPointer(); system("pause"); return 0; }

运行结果:
在这里插入图片描述
其中注意点:
1.类模板的声明与实现要在同一个文件中(原因是因为:c++标准中规定的模板类的在不用到它的时候不会被具现出来,编译后的链接时会出现问题。)解答源自:https://blog.csdn.net/qq_37623612/article/details/79473627

假如调用GetObjPtr()需要手动释放掉,这种的原因在于,用于特殊情况,需要自己手动删掉指针,为这种情况下提供接口(一般不建议使用)
作者:Giser_D



c+ 智能指针 C++ 指针

需要 登录 后方可回复, 如果你还没有账号请 注册新账号