C++11: smart pointer
来源:互联网 发布:知乎大神 微博 编辑:程序博客网 时间:2024/05/16 07:44
#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
- [C++] smart pointer
- C++11: smart pointer
- C++:智能指针(Smart Pointer)
- 【C++】智能指针(Smart Pointer)
- Smart Pointer
- Smart pointer
- smart pointer
- Smart Pointer
- Smart Pointer
- Smart pointer
- smart pointer
- smart pointer
- smart pointer
- smart pointer
- smart pointer / shared pointer / normal pointer
- Smart Pointer访谈录
- Smart Pointer--智能指针
- Smart Pointer访谈录
- android - Animation and Graphics(OverView)
- Assembly x64 Intro - View Assemble Variable by GDB
- HTML5 本地裁剪图片并上传至服务器
- HTTP 请求工具类
- 程序员也要学会沟通
- C++11: smart pointer
- 客户端认证自签名HTTPS证书
- 【REST】REST和JAX-RS相关知识介绍
- 训练集(train),测试集(test),验证集(validation)
- Android崩溃(一):小红点BadgeView导致的崩溃
- 交换机介绍
- iOS开发中更改应用程序启动图片
- MAC在Finder栏显示所浏览文件夹路径的方法
- C语言getopt()函数的使用