home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / c / library / dos / diverses / tctnt / nu.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-27  |  1.4 KB  |  56 lines

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