home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C12 / Copymem.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  924 b   |  43 lines

  1. //: C12:Copymem.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Duplicate during assignment
  7. #include "../require.h"
  8. #include <cstdlib>
  9. #include <cstring>
  10. using namespace std;
  11.  
  12. class WithPointer {
  13.   char* p;
  14.   static const int blocksz = 100;
  15. public:
  16.   WithPointer() {
  17.     p = (char*)malloc(blocksz);
  18.     require(p != 0);
  19.     memset(p, 1, blocksz);
  20.   }
  21.   WithPointer(const WithPointer& wp) {
  22.     p = (char*)malloc(blocksz);
  23.     require(p != 0);
  24.     memcpy(p, wp.p, blocksz);
  25.   }
  26.   WithPointer&
  27.   operator=(const WithPointer& wp) {
  28.     // Check for self-assignment:
  29.     if(&wp != this)
  30.       memcpy(p, wp.p, blocksz);
  31.     return *this;
  32.   }
  33.   ~WithPointer() {
  34.     free(p);
  35.   }
  36. }; 
  37.  
  38. int main() {
  39.   WithPointer p;
  40.   WithPointer p2 = p; // Copy construction
  41.   p = p2; // Assignment
  42. } ///:~
  43.