I l @ ve RuBoard |
Difficulty: 6 In the third part of this miniseries, we examine the effect of references and iterators into a copy-on-write string. Can you spot the issues? Consider the copy-on-write Optimized::String class from Item 14, but with two new functions: Length() and operator[]() . namespace Optimized { class StringBuf { public: StringBuf(); // start off empty ~StringBuf(); // delete the buffer void Reserve( size_t n ); // ensure len >= n char* buf; // allocated buffer size_t len; // length of buffer size_t used; // # chars actually used unsigned refs; // reference count private: // No copying... // StringBuf( const StringBuf& ); StringBuf& operator=( const StringBuf& ); }; class String { public: String(); // start off empty ~String(); // decrement reference count // (delete buffer if refs==0) String( const String& ); // point at same buffer and // increment reference count void Append( char ); // append one character size_t Length() const; // string length char& operator[](size_t);// element access const char operator[](size_t) const; // ... operator=() etc. omitted ... private: void AboutToModify( size_t n ); // lazy copy, ensure len>=n StringBuf* data_; }; } This allows code such as the following: if( s.Length() > 0 ) { cout << s[0]; s[0] = 'a'; } Implement the new members of Optimized::String . Do any of the other members need to be changed because of the new member functions? Explain. |
I l @ ve RuBoard |