fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Tracer {
  5. static int nextid;
  6. int id;
  7. public:
  8. Tracer () : id(++nextid) {
  9. cout<<"Tracer "<<id<<" created"<<endl;
  10. }
  11. ~Tracer() {
  12. cout<<"Tracer "<<id<<" destroyed"<<endl;
  13. }
  14. };
  15. int Tracer::nextid =0;
  16.  
  17. int main()
  18. {
  19. {
  20. struct Simple { Tracer i; } s;
  21. s.i.~Tracer(); // not needed if integer.
  22. new (&s.i) Tracer; // the lifecyle of the newly created object
  23. // will auto, since Simple will be destroyed when
  24. // going out of scope
  25. }
  26. cout << "Simple went out of scope"<<endl;
  27.  
  28. {
  29. struct Complex { char s[256]; } c;
  30. Tracer *p = new (&c.s) Tracer; // the lifecycle of the newly created object
  31. // is dynamic. You'll need to delete it in time.
  32. // because compiler doesn't know about its true nature
  33. // and memory will be lost when going out of scope
  34. p->~Tracer();
  35. }
  36. cout << "Complex went out of scope"<<endl;
  37. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Tracer 1 created
Tracer 1 destroyed
Tracer 2 created
Tracer 2 destroyed
Simple went out of scope
Tracer 3 created
Tracer 3 destroyed
Complex went out of scope