C++my_auto_ptr类

网友投稿 249 2022-09-30

C++my_auto_ptr类

my_auto_ptr通过它的析构函数来调用delete删除某对象的指针,来达到自动释放内存,而不需要显示的调用delete某对象。(1)实现自动释放#include #include 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 #include 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 #include 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 {};templateclass 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 ptr1(new People); my_auto_ptr ptr2(new Student); return 0;}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Azure Virtual Desktop-7-利用ADFS实现SSO单点登录-共享密钥标识
下一篇:SpringBoot前后端分离实现个人博客系统
相关文章

 发表评论

暂时没有评论,来抢沙发吧~