zoukankan      html  css  js  c++  java
  • 32.智能指针auto_ptr

     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 }
  • 相关阅读:
    数据存储 twisted
    数据存储 mongodb
    数据存储 redis
    数据存储 txt
    同时使用有线内网与无线外网
    使用xshell从服务器下载文件
    everything使用技巧
    【吴恩达机器学习】第8章 正则化
    python文件重命名
    【统计学习】 第5章 决策树
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8650735.html
Copyright © 2011-2022 走看看