Make sure lifetime of helper structs is less than owning struct

Imperatorn johan_forsberg_86 at hotmail.com
Mon Nov 15 22:25:03 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;
> }
> ```

Maybe a candidate for the "d idioms" page


More information about the Digitalmars-d-learn mailing list