#include using namespace std; class MyString { public: MyString(); MyString(const char*); MyString(MyString const& s); MyString& operator= (MyString const& s); ~MyString(); char getChar(const int& i) const; void setChar(const int& i, const char& c); void print() const; private: class Data { public: Data(); Data(const char*); Data(Data const& d); char* text_; unsigned count_; // Number of references to this object }; Data* data_; }; MyString::Data::Data() : count_(1) { // Set text_ as a new char array that contains only the string terminator \0 } MyString::Data::Data(const char* s) : count_(???) { // Init count_ to correct value // Set text_ as a new char array with length one larger than s (to accomodate the \0), then // copy data from s to text_ } MyString::Data::Data(Data const& d) : count_(???) { // Init count_ to correct value // As above, but copy from the text_ field of d } MyString::MyString() : data_(new Data()) { } MyString::MyString(const char* s) : // As above, but initialise data_ by forwarding on the argument s MyString::MyString(MyString const& s) : data_(s.data_) { // Increment the reference count for data_ } MyString& MyString::operator= (MyString const& s) { // DO NOT CHANGE THE ORDER OF THESE STATEMENTS! Data* const old = data_; data_ = s.data_; ++data_->count_; // Decrement the count of old // If the count of old is now 0, delete it return *this; } MyString::~MyString() { // Decrease the reference count and delete data_ if the count is down to zero if (--data_->count_ == 0) delete data_; } char MyString::getChar(const int& i) const { return *(data_->text+i); } void MyString::setChar(const int& i, const char& c) { // This method might need to change things in *data_ // Thus it first checks if this is the only pointer to *data_ if (data_->count_ > 1) { Data* d = new Data(*data_); // Invoke Fred::Data's copy ctor // Decrease the count of data // Point data_ at the new object } data_->text[i] = c; } void MyString::print() const { cout << data_->text << " [" << data_->count_ << "]" << endl; }