Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operating on dynamic memory, is it meaningful to overload a const memeber function?

An exercise from C++ Primer 5 Edition made me stuck, which goes like

Exercise 12.3: Does this class need const versions of push_back and pop_back? If so, add them. If not, why aren’t they needed? (Page 458)

Below is the class. Definitions for members front and back are omitted to simplify the 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 a const member void StrBlob::pop_back() const as below.

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

Compiler complained nothing about this const member. wondering am I doing right? Is there any possibility that this const member can be called? Is it meaningful to add this const member? Why?

like image 688
Yue Wang Avatar asked Dec 22 '13 01:12

Yue Wang


1 Answers

You can certainly do this if you want to, but there doesn't seem to be any logical reason. The compiler doesn't complain because this doesn't modify data (which is a pointer) but rather the thing data points to, which is perfectly legal to do with a const pointer.

like image 127
David Schwartz Avatar answered Dec 07 '22 23:12

David Schwartz