#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <memory>
using namespace std;
//智能指针自动回收内存 不用delete或者显式调用析构函数
class A{
public:
A(int a){
cout<<"this is A(int a)----"<<endl;
this->m_a=a;
}
void printA(){
cout<<"m_a: "<<this->m_a<<endl;
}
~A(){
cout<<"this is ~A()------"<<endl;
}
private:
int m_a;
};
class MyAutoPtr{
public:
MyAutoPtr(A *ptr){
this->m_ptr = ptr;
}
~MyAutoPtr(){
if(this->m_ptr!=NULL){
delete m_ptr;
this->m_ptr=NULL;
}
}
A* operator->(){
return this->m_ptr;
}
A& operator*(){
return *this->m_ptr;
}
private:
A *m_ptr;
};
void test(){
/*auto_ptr<A> ptr(new A(10));
ptr->printA();*/
#if 0
A *aa = new A(10);
aa->printA();
delete aa;
#endif
};
void test2(){
MyAutoPtr ptr(new A(20));
ptr->printA(); //重载->操作符
(*ptr).printA();//重载*操作符
}
int main(){
/*auto_ptr<int> ptr(new int);
*ptr=10;
cout<<"*ptr----"<<*ptr<<endl;*/
//test();
test2();
system("pause");
return 0;
}
自定义智能指针
最新推荐文章于 2024-06-29 23:10:44 发布