Reimplement the Str class, but choose an implementation strategy that requires that the class manage the storage itself. For example, you might store an array of char and a length. Consider what implications this change in design has for copy control. Also consider the cost of using Vec, (e.g., in storage overhead).
Code:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
class Str{
friend
istream& operator>>(istream&, Str&);
public:
Str& operator+=(const Str& s){
copy(s.data, s.data + s.length, data + length);
return *this;
}
typedef size_t size_type;
Str():length(0) {}
Str(size_type n, char c) {
for (length = 0; length != n; data[length++] = c);
}
Str(const char *s) {
copy(s, s + strlen(s), data + length);
}
char& operator[](size_type i){
return data[i];
}
const char& operator[](size_type i) const {
return data[i];
}
size_type size() const {
return length;
}
private:
char data[];
size_type length;
};
istream& operator>>(istream& is, Str& s){
s.length = 0;
char c;
while (is.get(c) && isspace(c));
if (is){
do
s.data[s.length++] = c;
while (is.get(c) && !isspace(c));
if (is)
is.unget();
}
return is;
}
ostream& operator<<(ostream& os, const Str& s){
for (Str::size_type i(0); i != s.size(); ++i)
os << s[i];
return os;
}