智能指针
1、 概念
堆内存的对象需要手动delete销毁,如果忘记使用delete销毁就会造成内存泄漏。
所以在C++ ISO 98标准中引入了智能指针的概念,并且在ISO11中趋于完善。
使用智能指针可以让堆内存对象具有栈内存对象的特性。原理时给需要自动回收的堆内存对象套上一个栈内存对象的模板。
C++有四种智能指针:
● auto_ptr 自动指针(C++ ISO 98 已废弃)
● unique_ptr 唯一指针(C++ ISO 11)
● shared_ptr 共享指针(C++ ISO 11)
● weak_ptr 协助指针(C++ ISO 11)
智能指针头文件,#include<memory>
2、 auto_ptr
#include <iostream>
#include <memory>
using namespace std;
class Test
{
private:
string s;
public:
Test(string s):s(s)
{
cout << s << "构造函数" << endl;
}
~Test()
{
cout << s << "析构函数" << endl;
}
void show()
{
cout << s << "执行程序" << endl;
}
};
int main()
{
{
Test *t1 = new Test("A");
// 创建一个栈内存智能指针对象ap1
auto_ptr<Test> ap1(t1); // ap1 管理t1
// 取出被管理的堆内存对象,并调用show成员函数
ap1.get()->show();
// 释放ap1智能指针对t1对象的控制权
// ap1.release();
// 创建B堆对象,B把A顶掉,A对象销毁
ap1.reset(new Test(