fork(1) download
  1. #include <stdio.h>
  2.  
  3. class Bar
  4. {
  5. public:
  6. Bar() { printf ("Bar::Bar\n"); }
  7. ~Bar() { printf ("Bar::~Bar\n"); }
  8. Bar(const Bar&) { printf("Bar::Bar(const Bar&)\n"); }
  9. void baz() const { printf("Bar::Baz\n"); }
  10. };
  11.  
  12. class Foo
  13. {
  14. Bar bar;
  15.  
  16. public:
  17. Bar& getBar () { return bar; }
  18. Foo() { }
  19. };
  20.  
  21. int main()
  22. {
  23. printf("This is safe:\n");
  24. {
  25. Foo *x = new Foo();
  26. const Bar y = x->getBar();
  27. delete x;
  28. y.baz();
  29. }
  30. printf("\nThis is a disaster:\n");
  31. {
  32. Foo *x = new Foo();
  33. const Bar& y = x->getBar();
  34. delete x;
  35. y.baz();
  36. }
  37. return 0;
  38. }
  39.  
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
This is safe:
Bar::Bar
Bar::Bar(const Bar&)
Bar::~Bar
Bar::Baz
Bar::~Bar

This is a disaster:
Bar::Bar
Bar::~Bar
Bar::Baz