智能指针不需要写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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。