何为智能指针,即不需要用户再自动手动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时可释放
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
实现文件
template
SmartPointer::SmartPointer(T* ptr_)
{
// 判断是否为空
if (ptr_)
{
m_ptr = ptr_;
m_count = 1;
}
else{
m_ptr = nullptr;
cout << “指针为空,无法实现智能指针” <<
C++ 手动实现简单的智能指针类
最新推荐文章于 2024-03-28 23:18:10 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)