placenew1.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // placenew1.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. pc3 = new (buffer) JustTesting("Bad Idea", 6);
  33. pc4 = new JustTesting("Heap2", 10);
  34. cout << "Memory contents:\n";
  35. cout << pc3 << ": ";
  36. pc3->Show();
  37. cout << pc4 << ": ";
  38. pc4->Show();
  39. delete pc2; // free Heap1
  40. delete pc4; // free Heap2
  41. delete [] buffer; // free buffer
  42. cout << "Done\n";
  43. // std::cin.get();
  44. return 0;
  45. }