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