home *** CD-ROM | disk | FTP | other *** search
- #if 0
- From:
- Subject: Destructors for for-loop iterator-expressions are wrong
- Status: Fixed in ZTC++ 2.2
- #endif
-
- //_ bug52.cpp
- // If the iterator-expression of a for-loop (3rd part)
- // uses a temporary object of a class with a destructor,
- // the destructor for this temporary object might be
- // called even if the corresponding constructor is never
- // called because the loop body (and the iterator) is
- // never executed.
- //
- // This does _NOT_ occur if the for-loop is replaced by
- // the exactly equivalent while-loop.
- //
- // Workaround:
- // Never use a for-loop if the iterator contains an
- // expression involving class objects with inherited
- // or explicit destructors.
-
- #include <stdio.h>
-
- struct A {
- A();
- ~A();
- };
-
- A::A()
- { printf("constructor %p\n",this); }
-
- A::~A()
- { printf("destructor %p\n",this); }
-
- int fcn() { return 0; }
-
- struct B {
- B();
- A x;
- A f();
- };
-
- A B::f() { A y; return y; }
-
- B::B()
- {
- #ifndef BUG_FREE
- for (; fcn(); x = f()) {
- if (fcn())
- break;
- }
- /* output (bad):
- constructor 29fc
- destructor 29ee <- bad destructor call
- destructor 29fc
- */
- #else
- while (fcn()) {
- if (fcn())
- break;
- x = f();
- }
- /* output (ok):
- constructor 29fc
- destructor 29fc
- */
- #endif
- }
-
- void main()
- {
- B z;
- fcn();
- }
-