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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With