D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 6659 - Destructor in range foreach called after initialization
Summary: Destructor in range foreach called after initialization
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 major
Assignee: No Owner
URL:
Keywords: pull, wrong-code
Depends on:
Blocks:
 
Reported: 2011-09-13 00:11 UTC by Martin Nowak
Modified: 2012-03-28 22:52 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Martin Nowak 2011-09-13 00:11:52 UTC
void main()
{
    static struct Iter
    {
        ~this()
        {
            ++_dtor;
        }

        bool opCmp(ref const Iter rhs) { return _pos == rhs._pos; }
        void opUnary(string op:"++")() { ++_pos; }
        size_t _pos;

        static size_t _dtor;
    }

    foreach(ref iter; Iter(0) .. Iter(10))
    {
        assert(Iter._dtor == 0);
    }
    assert(Iter._dtor == 2);
}

---

The iteration is done using destructed instances.
Comment 1 Kenji Hara 2012-03-23 05:52:32 UTC
A foreach range statement:

foreach (iter; lower .. upper) {}

is always translated to a for statement:

for (auto iter = lower, limit = upper; iter != upper; ++iter) {}

So, this is a lifetime issue declared in for statement Initialize part.
Comment 3 github-bugzilla 2012-03-28 21:42:31 UTC
Commit pushed to master at https://github.com/D-Programming-Language/dmd

https://github.com/D-Programming-Language/dmd/commit/b5aa4bc4cdb52ed6996e0afab9368fa6d0ae5934
Merge pull request #826 from 9rnsr/fix6659

fix Issue 6659 - Destructor in range foreach called after initialization