Bug 17470 – [scope] this has longer lifetime than this

Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
Linux
Creation time
2017-06-05T16:01:00Z
Last change time
2017-06-05T17:02:44Z
Assigned to
uplink.coder
Creator
uplink.coder

Comments

Comment #0 by uplink.coder — 2017-06-05T16:01:26Z
The following code: @safe struct X { byte[] s; byte[9] a; this(int n) { assert(n < 9); s = a[0 .. n]; } } raises the error t.d(8): Error: address of variable this assigned to this with longer lifetime While infact, this has the exact same lifetime as this (it's the same pointer)
Comment #1 by dlang-bugzilla — 2017-06-05T16:07:00Z
I think the compiler is correct in issuing the error, though the error message might need improvement. The problem is that you are creating an internal pointer to the struct, which is forbidden. Since structs are value types, constructing an instance of X on the stack, then returning it, will cause the s field to refer to invalid memory.
Comment #2 by uplink.coder — 2017-06-05T16:24:39Z
This is already fixed in the stable branch.
Comment #3 by dlang-bugzilla — 2017-06-05T16:39:25Z
(N.B. Use WORKSFORME instead of FIXED for bugs that shouldn't appear in the changelog)
Comment #4 by uplink.coder — 2017-06-05T17:02:44Z
Apparently this error is valid because structs maybe moved. in which case `s` would contain a dangling pointer.