my_auto_ptr通过它的析构函数来调用delete删除某对象的指针,来达到自动释放内存,而不需要显示的调用delete某对象。
(1)实现自动释放
#include <iostream> #include <string> using namespace std; struct People { public: People() {cout << "People" << endl;} ~People() {cout << "~People" << endl;} void run(void) const {cout << "Peple can run!" << endl;} }; class my_auto_ptr { public: my_auto_ptr(People* p) : p(p) {} ~my_auto_ptr() {delete p;} private: People* p; }; int main(int argc, char *argv[]) { my_auto_ptr ptr(new People); return 0; }
程序输出:
People
~People
(2)实现调用该对象的成员
#include <iostream> #include <string> using namespace std; struct People { public: People() {cout << "People" << endl;} ~People() {cout << "~People" << endl;} void run(void) const {cout << "Peple can run!" << endl;} }; class my_auto_ptr { public: my_auto_ptr(People* p) : p(p) {} ~my_auto_ptr() {delete p;} People* operator->() const {cout << "->" << endl; return p;} const People& operator*() const {cout << "*" << endl; return *p;} const People* operator&() const {cout << "&" << endl; return p;} private: People* p; }; int main(int argc, char *argv[]) { my_auto_ptr ptr(new People); ptr->run(); (*ptr).run(); &ptr; return 0; } /* 总结: ptr->run(); 这里ptr是一个my_auto_ptr对象,p->run的含义与(p.operator->())->run求值相同。 p.operator->()返回对People对象的指针,然后对返回的People调用run()函数。 */
程序输出:
People
->
Peple can run!
*
Peple can run!
&
~People
(3)实现泛型版本
#include <iostream> #include <string> using namespace std; struct People { public: People() {cout << "People" << endl;} ~People() {cout << "~People" << endl;} void run(void) const {cout << "Peple can run!" << endl;} }; class Student {}; template<typename T> class my_auto_ptr { public: my_auto_ptr(T* p) : p(p) {} ~my_auto_ptr() {delete p;} T* operator->() const {cout << "->" << endl; return p;} const T& operator*() const {cout << "*" << endl; return *p;} private: T* p; }; int main(int argc, char *argv[]) { my_auto_ptr<People> ptr1(new People); my_auto_ptr<Student> ptr2(new Student); return 0; }