placenew2.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // placenew2.cpp -- new, placement new, no delete
  2. #include <iostream>
  3. #include <string>
  4. #include <new>
  5. using namespace std;
  6. const int BUF = 512;
  7. class JustTesting
  8. {
  9. private:
  10. string words;
  11. int number;
  12. public:
  13. JustTesting(const string & s = "Just Testing", int n = 0)
  14. {words = s; number = n; cout << words << " constructed\n"; }
  15. ~JustTesting() { cout << words << " destroyed\n";}
  16. void Show() const { cout << words << ", " << number << endl;}
  17. };
  18. int main()
  19. {
  20. char * buffer = new char[BUF]; // get a block of memory
  21. JustTesting *pc1, *pc2;
  22. pc1 = new (buffer) JustTesting; // place object in buffer
  23. pc2 = new JustTesting("Heap1", 20); // place object on heap
  24. cout << "Memory block addresses:\n" << "buffer: "
  25. << (void *) buffer << " heap: " << pc2 <<endl;
  26. cout << "Memory contents:\n";
  27. cout << pc1 << ": ";
  28. pc1->Show();
  29. cout << pc2 << ": ";
  30. pc2->Show();
  31. JustTesting *pc3, *pc4;
  32. // fix placement new location
  33. pc3 = new (buffer + sizeof (JustTesting))
  34. JustTesting("Better Idea", 6);
  35. pc4 = new JustTesting("Heap2", 10);
  36. cout << "Memory contents:\n";
  37. cout << pc3 << ": ";
  38. pc3->Show();
  39. cout << pc4 << ": ";
  40. pc4->Show();
  41. delete pc2; // free Heap1
  42. delete pc4; // free Heap2
  43. // explicitly destroy placement new objects
  44. pc3->~JustTesting(); // destroy object pointed to by pc3
  45. pc1->~JustTesting(); // destroy object pointed to by pc1
  46. delete [] buffer; // free buffer
  47. // std::cin.get();
  48. return 0;
  49. }