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

ag0aep6g anonymous at example.com
Tue Mar 13 21:07:33 UTC 2018


On Tuesday, 13 March 2018 at 20:49:16 UTC, Nathan S. wrote:
> "onlineapp.d(16): Error: address of variable this assigned to 
> this with longer lifetime"
>
> ```d
[...]
> struct SmallString
> {
>     char[24] small;
>     char[] data;
[...]
>     this(scope const(char)[] s) @safe
>     {
[...]
>             data = small[0 .. s.length];
[...]
>     }
> }
[...]
> ```

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.


More information about the Digitalmars-d-learn mailing list