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