C++ Primer : 第十二章 : 动态内存之shared_ptr类实例:StrBlob类

时间:2023-12-20 19:48:08

StrBlob是一个管理string的类,借助标准库容器vector,以及动态内存管理类shared_ptr,我们将vector保存在动态内存里,这样就能在多个对象之间共享内存。

定义StrBlob类:

#include <iostream>
#include <stdexcept>
#include <memory>
#include <vector>
#include <string>
#include <initializer_list>
#include <utility>
#include <stdexcept> // for out_of_range class StrBlob
{
public:
typedef std::vector<std::string>::size_type size_type;
typedef std::shared_ptr<std::vector<std::string>> shdptrStrVec; StrBlob();
StrBlob(std::initializer_list<std::string> il);
StrBlob(std::vector<std::string>::iterator& left, std::vector<std::string>::iterator& right);
StrBlob(std::vector<std::string>& vec); size_type size() const { return data->size(); }
bool empty() const { return data->empty();} void push_back(const std::string& str ){ data->push_back(str);}
void pop_back(); // 访问元素
std::string& front();
std::string& back();
// const 版本
const std::string& front() const;
const std::string& back() const; std::string& at(size_type i){ return data->at(i); } StrBlob& operator = (StrBlob& blob); private: std::shared_ptr<std::vector<std::string>> data; void check(size_type i, const std::string& msg) const;
};

StrBlob的实现:

StrBlob::StrBlob() : data(std::make_shared<std::vector<std::string>>())
{
} StrBlob::StrBlob(std::initializer_list<std::string> il) : data(std::make_shared<std::vector<std::string>> (il))
{
} StrBlob::StrBlob(std::vector<std::string>::iterator& left, std::vector<std::string>::iterator& right) : data(std::make_shared<std::vector<std::string>>(left, right)){ } StrBlob::StrBlob(std::vector<std::string>& vec) : data(std::make_shared<std::vector<std::string>>(vec)) {
} void StrBlob::check(size_type i, const std::string& msg) const
{
if (i >= data->size())
throw std::out_of_range(msg);
} std::string& StrBlob::front()
{
check(0, "");
return data->front();
} std::string& StrBlob::back()
{
check(0, "");
return data->back();
} const std::string& StrBlob::front() const
{
check(0, "");
return data->front();
} const std::string& StrBlob::back() const
{
check(0, "");
return data->back();
} void StrBlob::pop_back()
{
check(0, "");
data->pop_back();
} StrBlob& StrBlob::operator =(StrBlob& blob) { this->data = blob.data; return *this;
}