本文内容来自于对狄泰学院 唐佐林老师 C++深度解析 课程的学习总结
智能指针
智能指针 的意义
现代 C++ 开发库中 最重要的类模板之一
C++ 中 自动内存管理 的主要手段
能够在 很大程序 上避开内存相关的问题
STL 中的智能指针 auto_ptr
生命周期结束时,销毁指向的内存空间
不能指向堆数组,只能指向堆对象(变量)
一片堆空间只属于一个智能指针对象
多个智能指针对象 不能指向同一片堆空间
实验代码
auto_ptr 的使用
#include <iostream>
#include <string>
#include <memory>
using namespace std;
class Test
{
string m_name;
public:
/* 构造函数 */
Test(const char *name)
{
cout << "Hello, " << name << "." << endl;
m_name = name;
}
void print()
{
cout << "I' m" << m_name << endl;
}
~Test()
{
cout << "Goodbye, " << m_name << endl;
}
};
int main()
{
auto_ptr<Test> pt(new Test("lzg"));
cout << "pt = " << pt.get() << endl;
pt->print();
cout << endl;
auto_ptr<Test> pt1(pt);
cout << "pt = " << pt.get() << endl;
cout << "pt1 = " << pt1.get() << endl;
pt1->print();
return 0;
}
运行结果:
实验结果:STL 库中的 auto_ptr 智能指针无需手动释放堆内存,pt 和 pt1 完成了内存管理权转移
下面我们来自己来编写一个智能指针类模板
SmartPointer.h
#ifndef _SAMRTPOINTER_H_
#define _SAMRTPOINTER_H_
template <typename T>
class SmartPointer
{
T *mp;
public:
SmartPointer(T *p=NULL)
{
mp = p;
}
SmartPointer(const SmartPointer<T>& obj)
{
mp = obj.mp;
const_cast<SmartPointer<T>&>(obj).mp = NULL;
}
SmartPointer<T>& operator = (const SmartPointer<T>& obj)
{
if(this != &obj)
{
delete mp;
mp = obj.mp;
const_cast<SmartPointer<T>&>(obj).mp = NULL;
}
return *this;
}
T* operator -> ()
{
return mp;
}
T& operator * ()
{
return *mp;
}
bool isNull()
{
return (mp == NULL);
}
T* get()
{
return mp;
}
~SmartPointer()
{
delete mp;
}
};
#endif
将上次实验 main 中的 auto_ptr 换成我们自己写的 SmartPointer,
运行结果:
实现结果,两次的运行结果一模一样,说明我们成功的实现了智能指针类模板。
小结
智能指针 C++ 中 自动内存管理 的主要手段
智能指针在各种平台上都有不同的表现形式
智能指针能够 尽可能的避开 内存相关的问题
STL 和 QT 中都提供了对智能指针的支持