C++11: smart pointer

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

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

int main()
{
        StrBlob b1; 
        {   
                StrBlob b2 = {"a", "an", "the"};
                b1 = b2; 
                b2.push_back("about");
        }
        while (b1.size() > 0) {
                std::cout << b1.back() << " ";
                b1.pop_back();
        }
        std::cout << "\n";
        try {
                std::cout << b1.back();
        } catch (std::out_of_range &ex) {
                std::cout << "file: " << __FILE__ << " line: " << __LINE__
                          << " throw exception: " << ex.what() << std::endl;
        }   
        std::cout << "aaaaaa\n";
        return 0;
}

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)) { }

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

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

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

void StrBlob::check(size_type i, const std::string &msg) const
{
        if (i >= data->size()) {
                throw std::out_of_range(msg);
        }
}
// C++ primer 5th exercise 12.2(p.458)
// g++ xx.cpp -std=c++11
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值