智能指针类模板
- 最重要类模板之一
- 自动内存管理的主要手段
- 能在很大程度上避开内存相关的问题
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 << "T'm " << m_name << "." << endl;
}
~Test()
{
cout << "goodby ." << m_name << "." << endl;
}
};
int main()
{
auto_ptr<Test> pt(new Test("chen"));
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;
}
61-1.cpp: In function ‘int main()’:
61-1.cpp:29:2: warning: ‘template class std::auto_ptr’ is deprecated [-Wdeprecated-declarations]
auto_ptr pt(new Test(“chen”));
^~~~~~~~
In file included from /usr/include/c++/8/memory:80,
from 61-1.cpp:3:
/usr/include/c++/8/bits/unique_ptr.h:53:28: note: declared here
template class auto_ptr;
^~~~~~~~
61-1.cpp:37:2: warning: ‘template class std::auto_ptr’ is deprecated [-Wdeprecated-declarations]
auto_ptr pt1(pt);
^~~~~~~~
In file included from /usr/include/c++/8/memory:80,
from 61-1.cpp:3:
/usr/include/c++/8/bits/unique_ptr.h:53:28: note: declared here
template class auto_ptr;
^~~~~~~~
???
STL中其他智能指针
QT中的智能指针
- QPointer
- 当其指向的对象销毁时,他会被自动置空
- 析构时不会自动销毁锁指向的对象
- QSharedPointer
- 引用计数型智能指针
- 可以被自由的拷贝和赋值
- 当引用计数为0时才能删除指向的对象
第61课第二节
- QT中的智能指针没学
自己实现智能指针
#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)//拷贝构造函数
{
//delete mp;
mp = obj.mp;//将自己的堆空间装给当前对象
const_cast<SmartPointer<T>&>(obj).mp = NULL; //去常
}
SmartPointer& 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
#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 << "T'm " << m_name << "." << endl;
}
~Test()
{
cout << "goodby ." << m_name << "." << endl;
}
};
int main()
{
SmartPointer<Test> pt(new Test("chen"));
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;
}
小结
- 智能指针C++中自动内存管理的主要手段
- 能在很大程度上避开内存相关的问题
- 智能指针在各种平台上都有不同的表现形式
- STL和QT中都提供了对智能指针的支持