12.1.1

12.1

b1有4个元素
b2已经不存在了

12.2

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

class StrBlob {
public:
    using size_type = std::vector<std::string>::size_type;
    StrBlob():data(std::make_shared<std::vector<std::string>>() ){}
    StrBlob(std::initializer_list<std::string> il):data(std::make_shared<std::vector<std::string>>(il) ) {}

    size_type size() const { return data->size(); }
    bool empty() { return data->empty(); }

    void pushback(const std::string &t) { data->push_back(t); }
    void popback() {
        check(0, "pop_back on empty StrBlob");
        data->pop_back();
    }
    std::string& front() {
        check(0, "front on empty StrBlob");
        return data->front();
    }
    std::string& back() {
        check(0, "back on empty StrBlob");
        return data->back();
    }
    const std::string& front() const {
        check(0, "front on empty StrBlob");
        return data->front();
    }
    const std::string& back() const {
        check(0, "back on empty StrBlob");
        return data->back();
    }

private:
    std::shared_ptr<std::vector<std::string> > data;

    void check(size_type i, const std::string &msg) const {
        if (i >= data->size()) {
            throw std::out_of_range(msg);
        }
    }

};

12.3
不需要
push_back和pop_back明显要改变容器的,虽然StrBlob类中的是指针,但是你给一个要改变的操作加const明显不合情理

12.4

std::vector<std::string>::size_type是unsigned的,所以它一定不小于0

12.5
使用explicit避免隐式转换,有点是目的更明确,更不易出错
缺点是,有时候我们希望隐式转换让代码更简洁一些,而使用explicit会复杂很多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值