Make sure lifetime of helper structs is less than owning struct

Sebastiaan Koppe mail at skoppe.eu
Mon Nov 15 19:24:56 UTC 2021


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;
}
```


More information about the Digitalmars-d-learn mailing list