智能指针练习

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