#include<iostream>
#include<memory>//智能指针在其中
using namespace std;
class A
{
public:
A(int a)
{
cout << "A()..." << endl;
this->a = a;
}
void func()
{
cout << "a = " << this->a << endl;
}
~A() {
cout << "~A()..." << endl;
}
private:
int a;
};
//将智能指针的类写出来
class MyAutoPtr
{
public:
MyAutoPtr(A *ptr)//这里不能用void * ,即万能指针。
//要指明数据类型,才能触发析构。
{
this->ptr = ptr;
}
~MyAutoPtr() {
if (this->ptr !=NULL)
{
cout << "delete ptr" << endl;
delete ptr;
this->ptr = NULL;
}
}
//为了实现my_p.ptr->func();,即返回指针ptr
A* operator->()
{
return this->ptr;
}
//为了实现(*ptr).func();,即返回对象
A & operator*()
{
return *ptr;
}
private:
A *ptr;
};
//常规写法
void test1()
{
A *ap = new A(10);
ap->func();
(*ap).func();//也可以这样调用
delete ap;
}
//使用智能指针
void test2()
{
auto_ptr<A> ptr(new A(10));//将a=10传入构造函数
ptr->func();
(*ptr).func();
//不用delete,会自动触发析构函数,自动回收,类似java的new对象
}
//自定义智能指针
void test3()
{
MyAutoPtr my_p(new A(10));//将a=10传入构造函数
my_p->func();//使用->操作符重载,为了使my_ptr对象,产生指针的效果
//my_p.ptr->func(); 注意my_p是个对象
(*my_p).func();//使用*操作符重载,为了使my_ptr对象,产生指针的效果
//*ptr.func();
}
int main()
{
int *p = new int;
//*p = 20;
//delete p;//需要手动删除开辟空间,而java等其他语言不需要
//智能指针是个类auto_ptr,调用构造函数ptr(new int),数据类型auto_ptr<int>
auto_ptr<int> ptr(new int);//智能指针,不需要手动delete,会自动回收
*ptr = 20;
test1();
cout << "-----------------------" << endl;
test2();
cout << "-----------------------" << endl;
test3();
return 0;
}
结果:
总结:
#include//智能指针头文件
智能指针是个类auto_ptr,调用构造函数ptr(new int),数据类型auto_ptr
auto_ptr ptr(new int);//智能指针,不需要手动delete,会自动触发析构函数,自动回收,类似java的new对象