智能指针

来源:互联网 发布:hr管理软件知乎 编辑:程序博客网 时间:2024/05/17 05:18

#define  _CRT_SECURE_NO_WARNINGS #include <iostream>#include <memory>using namespace std;class A{public:A(int a) {cout << "A(int)" << endl;this->a = a;}void func(){cout << "a = " << a << endl;}~A() {cout << "~A()" << endl;}private:int a;};class MyAutoPtr{public:MyAutoPtr(A * p){this->ptr = p;}~MyAutoPtr() {if (this->ptr != NULL) {delete this->ptr;}}//重载->操作符A* operator->(){return this->ptr;}//重载*操作符A& operator*(){return *ptr;}private:A * ptr;};//智能指针void test1(){#if 0A* p = new A(10);p->func();delete p;#endif#if 0auto_ptr<A> ptr(new A(10));ptr->func();#endifMyAutoPtr myPtr(new A(10)); //myPtr->func();(*myPtr).func();}int main(void){test1();return 0;}