打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
c++中智能指针自动删除new出来的对象以及写一个智能指针
智能指针不需要写delete 指针对象 ,就会自动析构函数,不论你有没有异常
  1 #include <iostream>
  2 #include <memory>
  3 #include <cstdio>
  4
  5 using namespace std;
  6 class A{
  7 public:
  8     A(int data = 0):m_data(data){
  9         cout << "A构造:" << this << endl;
 10     }
 11     ~A(void){
 12         cout << "A析构:" << this << endl;
 13     }
 14 private:
 15     int m_data;
 16 };
 17 int foo(void){
 18     //A* pa = new A;
 19     // ...
 20     auto_ptr<A> pa(new A);  //智能指针
 21     FILE* fp = fopen("none","r");
 22     if(!fp){
 23         perror("fopen");
 24         //delete pa;
 25         return -1;
 26     }
 27     //delete pa;
 28    return 0;
 29 }
 30 int main(void){
 31     foo();
 32     return 0;
 33
 34 }

tarena@ubuntu:~/stl/day02$ ./a.out
A构造:0xd9a010
fopen: No such file or directory
A析构:0xd9a010


​做一个智能指针
​ 1 #include <iostream>
  2 #include <memory>
  3 #include <cstdio>
  4
  5 using namespace std;
  6 class A{
  7 public:
  8     A(int data = 0):m_data(data){
  9         cout << "A构造:" << this << endl;
 10     }
 11     ~A(void){
 12         cout << "A析构:" << this << endl;
 13     }
 14 private:
 15     int m_data;
 16 };
 17 template<typename T>
 18 class AutoPtr{
 19 public:
 20     AutoPtr(T* p = NULL):m_p(p){
 21
 22     }
 23     ~AutoPtr(void){
 24         delete m_p;
 25     }
 26 private:
 27     T* m_p;
 28 };
 29 int foo(void){
 30     //A* pa = new A;
 31     // ...
 32     //auto_ptr<A> pa(new A);
 33     AutoPtr<A> pa(new A);
 34     FILE* fp = fopen("none","r");
 35     if(!fp){
 36         perror("fopen");
 37         //delete pa;
 38         return -1;
 39     }
 40     //delete pa;
 41    return 0;
 42 }
 43 int main(void){
 44     foo();
 45     return 0;
​ 46
 47 }
      
tarena@ubuntu:~/stl/day02$ ./a.out
A构造:0xd9a010
fopen: No such file or directory
A析构:0xd9a010

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
c 11新特性之智能指针
C 内存管理详解
C++内存管理
new,delete和指针
C++内存管理详解(3)
[转载]C++指针new和malloc区别
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服