home *** CD-ROM | disk | FTP | other *** search
/ Black Box 4 / BlackBox.cdr / progc / fixed300.arj / BUG52.CPP < prev    next >
Encoding:
C/C++ Source or Header  |  1991-03-26  |  1.6 KB  |  76 lines

  1. #if 0
  2. From:
  3. Subject: Destructors for for-loop iterator-expressions are wrong
  4. Status: Fixed in ZTC++ 2.2
  5. #endif
  6.  
  7. //_ bug52.cpp
  8. // If the iterator-expression of a for-loop (3rd part)
  9. // uses a temporary object of a class with a destructor,
  10. // the destructor for this temporary object might be
  11. // called even if the corresponding constructor is never
  12. // called because the loop body (and the iterator) is
  13. // never executed.
  14. //
  15. // This does _NOT_ occur if the for-loop is replaced by
  16. // the exactly equivalent while-loop.
  17. //
  18. //                  Workaround:
  19. // Never use a for-loop if the iterator contains an
  20. // expression involving class objects with inherited
  21. // or explicit destructors.
  22.  
  23. #include <stdio.h>
  24.  
  25. struct A {
  26.         A();
  27.         ~A();
  28. };
  29.  
  30. A::A()
  31. { printf("constructor %p\n",this); }
  32.  
  33. A::~A()
  34. { printf("destructor %p\n",this); }
  35.  
  36. int fcn() { return 0; }
  37.  
  38. struct B {
  39.         B();
  40.         A x;
  41.         A f();
  42. };
  43.  
  44. A B::f() { A y; return y; }
  45.  
  46. B::B()
  47. {
  48. #ifndef BUG_FREE
  49.         for (; fcn(); x = f()) {
  50.                 if (fcn())
  51.                         break;
  52.         }
  53.         /* output (bad):
  54.                 constructor 29fc
  55.                 destructor 29ee     <- bad destructor call
  56.                 destructor 29fc
  57.         */
  58. #else
  59.         while (fcn()) {
  60.                 if (fcn())
  61.                         break;
  62.                 x = f();
  63.         }
  64.         /* output (ok):
  65.                 constructor 29fc
  66.                 destructor 29fc
  67.         */
  68. #endif
  69. }
  70.  
  71. void main()
  72. {
  73.         B z;
  74.         fcn();
  75. }
  76.