Bug 68003 - Variable declared in condition in for loop is destroyed too soon
Summary: Variable declared in condition in for loop is destroyed too soon
Status: RESOLVED DUPLICATE of bug 86769
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 6.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: wrong-code
Depends on:
Blocks:
 
Reported: 2015-10-17 13:08 UTC by Eelis
Modified: 2020-10-28 15:38 UTC (History)
6 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail: 5.3.0, 6.1.0, 7.0
Last reconfirmed: 2016-12-05 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Eelis 2015-10-17 13:08:05 UTC
Consider:

  #include <cassert>
  #include <iostream>

  struct X
  {
    bool alive = true;
    ~X() { alive = false; }

    explicit operator bool() const { return true; }
  } ;

  int main()
  {
    for(int i = 0; X x = X(); assert(x.alive))
      if (++i == 3)
        break;
      else
        std::cout << i << std::endl;
  }

When compiled with gcc trunk, the program outputs:

  1
  a.out: t.cpp:14: int main(): Assertion `x.alive' failed.

When compiled with clang trunk, the program outputs:

  1
  2
Comment 1 Arthur O'Dwyer 2020-10-28 15:35:13 UTC
Confirmed. https://godbolt.org/z/MfbrcG
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86769 is a duplicate.
Comment 2 Marek Polacek 2020-10-28 15:38:38 UTC
PR86769 has a nicer test, so closing this one.  Thanks for finding the dup.

*** This bug has been marked as a duplicate of bug 86769 ***