Make sure lifetime of helper structs is less than owning struct
WebFreak001
d.forum at webfreak.org
Mon Nov 15 21:58:04 UTC 2021
On Monday, 15 November 2021 at 19:24:56 UTC, Sebastiaan Koppe
wrote:
> On Monday, 15 November 2021 at 15:56:57 UTC, WebFreak001 wrote:
>> is this currently possible or maybe possible with DIP1000?
>
> Yes it is. But besides `-dip1000` and `@safe`, it requires the
> use of a pointer:
>
> ```D
> @safe:
>
> struct ByChunk {
> FileReader* r;
> void popFront() {}
> }
>
> struct FileReader {
> ByChunk byChunk() return scope {
> return ByChunk(&this);
> }
> }
>
> void main() {
> ByChunk helper;
> {
> auto file = FileReader();
> helper = file.byChunk; // Error: address of variable
> `file` assigned to `helper` with longer lifetime
> }
> helper.popFront;
> }
> ```
awesome, such a simple solution! Also saves me the pain of
copying the struct data and avoiding copy constructor and stuff
by using a pointer.
More information about the Digitalmars-d-learn
mailing list