home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / IDIOMS.ZIP / 3-6.H < prev    next >
C/C++ Source or Header  |  1991-12-04  |  1KB  |  43 lines

  1. /* Copyright (c) 1992 by AT&T Bell Laboratories. */
  2. /* Advanced C++ Programming Styles and Idioms */
  3. /* James O. Coplien */
  4. /* All rights reserved. */
  5.  
  6. #include <stdlib.h>
  7. #include <string.h>
  8.  
  9. class StringRep {
  10. friend String;
  11. private:     // these are now accessible only to String
  12.     StringRep()           { *(rep = new char[1]) = '\e0'; }
  13.     StringRep(const StringRep& s)  {
  14.       ::strcpy(rep=new char[::strlen(s.rep)+1], s.rep);
  15.     }
  16.     StringRep& operator=(const StringRep& s) {
  17.        if (rep != s.rep) {
  18.          delete[] rep;
  19.          ::strcpy(rep=new char[::strlen(s.rep)+1], s.rep);
  20.        }
  21.        return *this;
  22.     }
  23.     ~StringRep()          { delete[] rep; }
  24.     StringRep(const char *s) {
  25.        ::strcpy(rep=new char[::strlen(s)+1], s);
  26.     }
  27.     StringRep operator+(const StringRep&) const;
  28.     int length() const    { return ::strlen(rep); }
  29. private:
  30.     char *rep;
  31.     int count;
  32. };
  33.  
  34. StringRep StringRep::operator+(const StringRep& s) const
  35. {
  36.     char *buf = new char[s.length() + length() + 1];
  37.     ::strcpy(buf, rep);
  38.     ::strcat(buf, s.rep);
  39.     StringRep retval( buf );
  40.     delete[] buf;         // get rid of temporary storage
  41.     return retval;
  42. }
  43.