初识智能指针:
8种:
auto_ptr(VC版)
auto_ptr(VS版或Linux版,符合标准C++)
Boost (Boost程序库完全开发指南.pdf):
scoped_ptr、scoped_array、shared_ptr、shared_array、weak_ptr、intrusive_ptr
智能指针:拿对象模拟指针,还负责内存的自动释放;
/
智能指针的核心问题在于拥有权管理和转移
8种:
auto_ptr(VC版)
auto_ptr(VS版或Linux版,符合标准C++)
Boost (Boost程序库完全开发指南.pdf):
scoped_ptr、scoped_array、shared_ptr、shared_array、weak_ptr、intrusive_ptr
智能指针:拿对象模拟指针,还负责内存的自动释放;
拥有权管理和转移
<span style="font-size:18px;">#include <iostream>
#include <memory>
#include <string>
using namespace std;
int main()
{
int *p = new int(10);
auto_ptr<int> pa(p); //delete p;
cout<<*pa<<endl; //*p
string *ps = new string("hello");
auto_ptr<string> pa1(ps); //delete ps;
cout<<pa1->size()<<endl; //p->
return 0;
}</span>
/
<span style="font-size:18px;">template <class _Ty>
class auto_ptr
{
public:
auto_ptr(_Ty *_P=0):_Owns(_P!=0),_Ptr(_P)
{}
~auto_ptr() //1.对象析构的时候释放指针所指的空间,即表现出智能指针的智能部分
{
if(_Owns)
delete _Ptr;
}
public:
_Ty& operator*()const //2.重载*p 和 p-> ,即表现出智能指针的指针部分
{
return *_Ptr;
}
_Ty* operator->()const
{
return _Ptr;
}
private:
bool _Owns;
_Ty *_Ptr;
};
class Test
{
public:
void fun()const
{
cout<<"This is Test fun()"<<endl;
}
};
int main()
{
int *p = new int(10);
auto_ptr<int> pa(p);
cout<<*pa<<endl;
Test *pt = new Test;
auto_ptr<Test> pa1(pt);
pal->fun();
return 0;
}</span>
智能指针的核心问题在于拥有权管理和转移