智能指针
智能指针是现代C++开发库中最重要的类模板之一,也是C++中自动内存管理的主要手段,能够在很大程度上避开内存相关的问题。
STL中的智能指针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("D.T.Software"));
//使用智能指针执行成员函数
cout << "pt = " << pt.get() << endl;
pt->print();
cout << endl;
//新定义一个智能指针,用原pt指针赋值
auto_ptr<Test> pt1(pt);
//原pt指针赋值后为空
cout << "pt = " << pt.get() << endl;
cout << "pt1 = " << pt1.get() << endl;
pt1->print();
return 0;
}
输出结果为:
Hello, D.T.Software.
pt = 0x7fb5ab402680
I'm D.T.Software.
pt = 0x0
pt1 = 0x7fb5ab402680
I'm D.T.Software.
Goodbye, D.T.Software.
STL中的其它智能指针
- shared_ptr
- 带有引用计数机制,支持多个指针对象指向同一片内存
- weak_ptr
- 配合shared_ptr而引入的一种智能指针
- unique_ptr
- 一个指针对象指向一片内存空间,不能拷贝构造和赋值
在最后来演示一个用类模板来模仿指针智能的实例:
#ifndef _SMARTPOINTER_H_
#define _SMARTPOINTER_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
使用函数(test.cpp):
#include <iostream>
#include <string>
#include "SmartPointer.h"
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()
{
//创建一个智能指针并指向test类
//使用智能指针来执行成员函数
SmartPointer<Test> pt(new Test("D.T.Software"));
cout << "pt = " << pt.get() << endl;
pt->print();
cout << endl;
//给另一个指针指针赋值
SmartPointer<Test> pt1(pt);
cout << "pt = " << pt.get() << endl;
cout << "pt1 = " << pt1.get() << endl;
pt1->print();
return 0;
}
运行结果为:
Hello, D.T.Software.
pt = 0x7fd773402680
I'm D.T.Software.
pt = 0x0
pt1 = 0x7fd773402680
I'm D.T.Software.
Goodbye, D.T.Software.