#include<iostream> #include<memory> using namespace std; class A { public: A(int id) { this->id = id; cout<<"A(int)"<<endl; } ~A() { cout<<"~A()"<<endl; } void print() { cout<<this->id<<endl; } private: int id; }; class Ptr { public: //传入一个对象的指针 Ptr(A *ptr) { this->ptr = ptr; } //匿名对象周期完毕自动释放 ~Ptr() { if(this->ptr!=NULL) { delete this-> ptr; this->ptr = NULL; cout<<"auto delete"<<endl; } } //返回的是一个对象指针 A* operator->() { return this->ptr; }1 //*p返回的就是对象 A& operator*() { //类中的ptr已经被初始化为A return *(this->ptr); } private: A *ptr; }; void test_auto_ptr() { //special grammer //匿名对象完成功能后,会自动调用类A的析构函数 auto_ptr<A> ptr(new A(11)); ptr->print(); } void test() { //A *a = new A(10);//这种简单的不delete会形成内存泄露 Ptr ptr(new A(12)); ptr->print(); (*ptr).print(); } int main(void) { test(); cout<<"===="<<endl; test_auto_ptr(); return 0; }