zoukankan      html  css  js  c++  java
  • 智能指针练习

    直接管理内存:使用new和delete

     1 #include<iostream>
     2 #include<vector> 
     3 using namespace std;
     4 
     5 vector<int>* new_vector(){
     6     //分配失败new会返回一个空指针 
     7     return new (nothrow) vector<int>;
     8 }
     9 //
    10 void read_ints(vector<int> *p){
    11     int v;
    12     while(cin>>v)
    13         p->push_back(v); 
    14 }
    15 //
    16 void print_ints(vector<int> *p){
    17     for(const auto &v: *p)
    18         cout<<v<<" ";
    19     cout<<endl;
    20 }
    21 int main(int argc,char **argv) {
    22     vector<int>* p =  new_vector();
    23     read_ints(p);
    24     print_ints(p);
    25     delete p;
    26     return 0;
    27 }

    使用shared_ptr而不是内置指针

    #include<iostream>
    #include<vector> 
    #include<memory>
    using namespace std;
    
    shared_ptr<vector<int>> new_vector(void){
        //使用make_shared分配内存 
        return  make_shared<vector<int>>();
    }
    //
    void read_ints(shared_ptr<vector<int>> p){
        int v;
        while(cin>>v)
            p->push_back(v); 
    }
    //
    void print_ints(shared_ptr<vector<int>> p){
        for(const auto &v: *p)
            cout<<v<<" ";
        cout<<endl;
    }
    int main(int argc,char **argv) {
        auto p =  new_vector();
        read_ints(p);
        print_ints(p);
        //delete p;    不用主动去分配内存 
        return 0;
    }
  • 相关阅读:
    异步IO数据库队列缓存
    requests.post发送字典套字典
    Git
    Django REST framework
    7. 函数-自定义函数
    6. 小数据池-编码-文件操作
    5. 基本数据结构-集合
    4. 基本数据结构-字典
    3. 基本数据结构-元组
    2. 基本数据结构-列表
  • 原文地址:https://www.cnblogs.com/wsl96/p/13096532.html
Copyright © 2011-2022 走看看