"Error: address of variable this assigned to this with longer lifetime"

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Mar 13 22:33:56 UTC 2018


On Tuesday, March 13, 2018 21:35:50 Nathan S. via Digitalmars-d-learn wrote:
> On Tuesday, 13 March 2018 at 21:07:33 UTC, ag0aep6g wrote:
> > You're storing a reference to `small` in `data`. When a
> > SmallString is copied, that reference will still point to the
> > original `small`. When the original goes out of scope, the
> > reference becomes invalid, a dangling pointer. Can't have those
> > in @safe code.
> >
> > The error message isn't exactly clear, though.
>
> The error does not go away when restoring these lines:
>
> ```
>      @disable this(this);
>      @disable void opAssign(this);
> ```

And you can't get rid of it, because the object can still be moved, which
would invalidate the pointer that you have referring to the static array. As
it stands, it simply does not work in D to have pointers (or dynamic arrays
which refer to) member variables of structs. With the use of scope and DIP
1000, they can work within restricted circumstances, but pretty much
anything that extends beyond a function call is going to have @safety
problems. To fix the problem, D would either need to provide a way to make
it illegal for a struct to be moved (which could cause a number of
problems), or it would have to provide hooks so that it would be possible to
do stuff like adjust pointers when an object is moved. There's a recent
discussion the problem here:

https://issues.dlang.org/show_bug.cgi?id=17448

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list