
回复
数据结构C++语言实现系列文章的代码实现不使用STL库,在智能指针、异常类、顶层父类三大基础类上进行代码实现,本文介绍智能指针类。
C++语言中没有垃圾回收机制,指针无法控制所指堆空间的生命周期,如果在动态申请堆空间后不释放堆空间,就会造成内存泄漏。
C++语言中提供了智能指针的方案解决内存泄漏的问题。使用智能指针,在指针生命周期结束时主动释放堆空间,一片堆空间最多由一个指针标识,同时杜绝指针运算和指针比较。
通过类模板(泛型编程)描述指针的行为,使用类模块就能够定义不同的指针对象。重载指针操作符”->”和”*”,利用智能指针对象模拟原生指针的行为。
#ifndef SMARTPOINTER_H_INCLUDED
#define SMARTPOINTER_H_INCLUDED
#include <iostream>
using namespace std;
template<typename T>
class SmartPointer
{
protected:
T *m_pointer;
public:
SmartPointer(T *p = NULL)
{
this->m_pointer = p;
cout << "construct function: SmartPointer()" << endl;
}
SmartPointer(const SmartPointer<T> &obj)
{
this->m_pointer = obj.m_pointer;
const_cast<SmartPointer<T>&>(obj).m_pointer = NULL;
cout << "copy construct function: SmartPointer(const SmartPointer<T> &obj)" << endl;
}
SmartPointer<T>& operator=(const SmartPointer<T> &obj)
{
if(this != &obj)
{
delete m_pointer;
this->m_pointer = obj.m_pointer;
const_cast<SmartPointer<T>&>(obj).m_pointer = NULL;
}
cout << "copy operation = function: SmartPointer<T>& operator=(const SmartPointer<T> &obj)" << endl;
return *this;
}
T *operator->()
{
return m_pointer;
}
T &operator*()
{
return *m_pointer;
}
T *get()
{
return m_pointer;
}
bool isFull()
{
return (m_pointer == NULL);
}
~SmartPointer()
{
cout << "deconstruct function:~SmartPointer()" << endl;
delete m_pointer;
}
};
#endif // SMARTPOINTER_H_INCLUDED
#include <iostream>
#include "SmartPointer.h"
using namespace std;
class Test
{
public:
Test(int num = 0):i(num)
{
cout << "construct function:Test()" << endl;
}
Test(Test &obj)
{
cout << "copy construct function Test(Test &obj)" << endl;
this->i = obj.value();
}
~Test()
{
cout << "deconstruct function: ~Test()" << endl;
}
int value()
{
return this->i;
}
private:
int i;
};
int main()
{
SmartPointer<Test> sp = new Test(3);
cout << sp->value() << endl;
cout << (*sp).value() << endl;
SmartPointer<Test> np;
np = sp;
cout << np->value() << endl;
cout << (*np).value() << endl;
cout << sp.isFull() << endl;
cout << np.isFull() << endl;
return 0;
}
智能指针只能用来指向堆空间中的单个对象或者变量,智能指针不能用来指向堆空间中的一个数组,也不能指向一个局部的对象或变量。
(1)指针特征操作符(->和*)可以被重载
(2)重载指针特征符能够使用对象代替指针
(3)智能指针只能用于指向堆空间中的内存
(4)智能指针的意义在于最大程度的避免内存问题
参考资料:《C++ primer》
《C++对象模型》
狄泰软件学院唐佐林老师课程
文章转载自公众号:汽车电子嵌入式