第十二章动态内存

1.shared_ptr,智能指针构造函数是显式的,不能将一个内置指针隐式转换为一个智能指针,必须直接初始化。

shared_ptr<int> p1(new int(42));

shared_ptr<int> p2 = new int (42);  //wrong

习题

12.2编写你自己的StrBlob 类,包含const 版本的 front 和 back

#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <initializer_list>
#include <exception>

using namespace std;

class StrBlob {
public:
    typedef vector<string>::size_type size_type;
    StrBlob();
    StrBlob(initializer_list<string> il):data(make_shared<vector<string>>(il)) { }
    size_type size() const { return data->size(); }
    bool empty() const { return data->empty(); }
    void push_back(const string &t);
    void pop_back();
    string front();
    const string front() const;
    string back();
    const string back() const;
private:
    shared_ptr<vector<string>> data;
    void check(size_type i, const string &msg) const {
        if (i >= data->size())
            throw std::out_of_range(msg);
    }

};

void StrBlob::pop_back()
{
    check(0, "pop_back on empty StrBlob");
    data->pop_back();
}

void StrBlob:: push_back(const string &t) {
    data->push_back(t); 
}

string StrBlob::front()
{
    check(0, "front on empty StrBlob");
    return data->front();
}

const string StrBlob::front() const 
{
    check(0, "front on empty StrBlob");
    return data->front();
}

string StrBlob::back()
{
    check(0, "back on empty StrBlob");
    return data->back();
}

const string StrBlob::back() const
{
    check(0, "back on empty StrBlob");
    return data->back();
}

int main()
{
    StrBlob sb{"a", "bb", "ccc"};
    cout << sb.front() << " " << sb.back() << endl;
}
View Code

 

12.7使用share_ptr,编写函数,返回一个动态分配的 int 的vector。将此vector 传递给另一个函数,这个函数读取标准输入,将读入的值保存在 vector 元素中。再将vector传递给另一个函数,打印读入的值。记得在恰当的时刻delete vector

#include <iostream>
#include <vector>
#include <memory>
#include <string>

using namespace std;

shared_ptr<vector<int>> fun()
{
    return std::make_shared<vector<int>>();
}

void use_fun(shared_ptr<vector<int>> p)
{
    int i;
    while(cin >> i)
        p->push_back(i);
}

int main()
{
    shared_ptr<vector<int>> myp = fun();
    use_fun(myp);
    for(int i : *myp)
        cout << i << endl;
    //delete myp;
    return 0;
}
View Code

 

posted @ 2021-05-31 17:10  11YS  阅读(27)  评论(0编辑  收藏  举报