Working with dynamic memory, does it make sense to overload the const memeber function?

The exercise from C ++ Primer 5 Edition made me stuck, which seems like

Exercise 12.3. Is const push_back and pop_back required for this class ? If yes, add them. If not, then why are they needed? (Page 458)

Below is the class. Definitions for members frontand backomitted to simplify codes.

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(); }
    // add and remove elements
    void push_back(const std::string &t) {data->push_back(t);}
    void pop_back();
    // element access
    std::string& front();
    std::string& back();
private:
    std::shared_ptr<std::vector<std::string>> data;
    // throws msg if data[i] isn't valid
    void check(size_type i, const std::string &msg) const;
};

StrBlob::StrBlob(): data(make_shared<vector<string>>()) { }
StrBlob::StrBlob(initializer_list<string> il):
          data(make_shared<vector<string>>(il)) { }

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

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

I tried to overload the const element void StrBlob::pop_back() constas shown below.

void StrBlob::pop_back() const
{
    check(0, "pop_back on empty wy_StrBlob");
    data->pop_back();
}

The compiler did not complain about this constant member. I wonder if I'm doing the right thing? Is there a chance that this constant member could be invoked? Can I add this constant member? What for?

+4
1

, , . , data ( ), data, const.

+7

All Articles