home *** CD-ROM | disk | FTP | other *** search
/ Turbo Toolbox / Turbo_Toolbox.iso / dtx9203 / borhot / nu.cpp < prev    next >
C/C++ Source or Header  |  1992-03-24  |  2KB  |  64 lines

  1. /* ------------------------------------------------------ */
  2. /*                       NU.CPP                           */
  3. /*       Demo of using pre-allocated memory with new      */
  4. /*              (c) 1991 Borland International            */
  5. /*                   All rights reserved.                 */
  6. /* ------------------------------------------------------ */
  7. /*            veröffentlicht in DOS toolbox 3'92          */
  8. /* ------------------------------------------------------ */
  9.  
  10. #include <iostream.h>
  11. #include <new.h>
  12.  
  13. class A {
  14.   public:
  15.     void * operator new(size_t size);
  16.     void * operator new(size_t size, void *ptr);
  17. };
  18.  
  19. /* ------------------------------------------------------ */
  20. /*  Overload new to allocate a block of                   */
  21. /*  memory of specified size of class.                    */
  22. /* ------------------------------------------------------ */
  23.  
  24. void * A::operator new(size_t size)
  25. {
  26.   void *ptr;
  27.   ptr=new unsigned char[size];
  28.   return ptr;
  29. }
  30.  
  31. /* ------------------------------------------------------ */
  32. /*  Overload new to accept a pre-allocated                */
  33. /*  pointer to a block of memory for a class.             */
  34. /* ------------------------------------------------------ */
  35.  
  36. void * A::operator new(size_t size, void *ptr)
  37. {
  38. #pragma warn -par
  39.       // we know size is never used!
  40.   cout << "new block\n";
  41.   return ptr;
  42. }
  43.  
  44. /* ------------------------------------------------------ */
  45.  
  46. int main()
  47. {
  48. #pragma warn -aus
  49.       // we know ch & y are assigned unused values!
  50.       // Pre-allocate a block of memory
  51.   void * buf=new (unsigned char[sizeof(A)]);
  52.  
  53.   cout << "before new\n";
  54.  
  55.   A *y;                 // Assign pre-allocated block of
  56.   y=new(buf) A;         // memory to a pointer of class A.
  57.  
  58.   A *ch;                // Allocate and assign a block of
  59.   ch=new A;             // memory to a pointer of class A.
  60.   return 0;
  61. }
  62. /* ------------------------------------------------------ */
  63. /*                   Ende von NU.CPP                      */
  64.