home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / IDIOMS.ZIP / 3-9.C < prev    next >
C/C++ Source or Header  |  1991-12-04  |  2KB  |  52 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 <string.h>
  7.  
  8. class StringRep {
  9. friend class String;
  10. private:    // private so it does not pollute global name space
  11.     typedef char *Char_p;
  12.     StringRep(StringRep::Char_p* const r) {
  13.         rep = *r; *r = 0; count = 1;
  14.     }
  15. public:
  16.     StringRep(const char *s)
  17.       { ::strcpy(rep = new char[::strlen(s)+1], s); count = 1; }
  18.     ~StringRep() { delete[] rep; }
  19. private:
  20.     char *rep;
  21.     int count;
  22. };
  23.  
  24. class String {
  25. public:
  26.     String()               { rep = new StringRep(""); }
  27.     String(const String& s) { rep = s.rep; rep->count++; }
  28.     String& operator=(const String& s) {
  29.        s.rep->count++;  if (--rep->count <= 0) delete rep;
  30.        rep = s.rep;
  31.        return *this;
  32.     }
  33.     ~String() { if (--rep->count <= 0) delete rep; }
  34.     String(const char *s)  { rep = new StringRep(s); }
  35.     String operator+(const String&) const;
  36.     int length() const     { return ::strlen(rep->rep); }
  37. private:
  38.     String(StringRep::Char_p* const r) {
  39.         rep = new StringRep(r);  // call new constructor
  40.     }
  41.     StringRep *rep;
  42. };
  43.  
  44. String String::operator+(const String& s) const
  45. {
  46.     char *buf = new char[s.length() + length() + 1];
  47.     ::strcpy(buf, rep->rep);
  48.     ::strcat(buf, s.rep->rep);
  49.     String retval( &buf );  // call the new private constructor
  50.     return retval;
  51. }
  52.