1 #include <iostream>
2 #include <memory>
3 #include <string>
4 #include <vector>
5 using namespace std;
6
7 struct my
8 {
9 int x;
10 int y;
11 };
12
13 //智能指针主要用于解决内存泄漏,拥有常规指针一样的使用,重载* ->运算符
14 void run1()
15 {
16 //void *p = malloc(1024 * 1024 * 100);
17 //智能指针,检测到没有使用就会自动释放
18 // auto_ptr<int>myp(new int[1024 * 1024 * 400]);
19 //*myp;//根据指针去内存,重载*
20
21 auto_ptr<my> my1(new my[100]);
22 cout << my1->x << endl;
23 }
24
25 void run()
26 {
27 //指针只能用构造函数初始化,用explicit拒绝auto_ptr<string> p = new string[100] 初始化
28 //智能指针可以创建指向STL的指针,但只能创建一个
29 auto_ptr<string> p(new string);
30 //创建多个会出错
31 //auto_ptr<string> p( new string[10] );
32 *p = "13456";
33
34 //string *p3 = new string[10];
35
36 //智能指针是浅拷贝(通过计数的方式决定所引用的空间是不是可以释放)
37 auto_ptr<string> p2(p);
38 cout << *p2 << endl;
39 //STL可以包含智能指针
40 vector<auto_ptr<int>> myv;
41 myv.push_back(auto_ptr<int>(new int[10]));
42 }
43
44 void main()
45 {
46 while (1)
47 {
48 run();
49 }
50 cin.get();
51 }