1. 程式人生 > >C++11: smart pointer

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