首页 > 其他 > 详细

智能指针练习

时间:2020-06-11 23:40:33      阅读:41      评论:0      收藏:0      [点我收藏+]

直接管理内存:使用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;
}

 

智能指针练习

原文:https://www.cnblogs.com/wsl96/p/13096532.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!