Make sure lifetime of helper structs is less than owning struct

Ali Çehreli acehreli at yahoo.com
Mon Nov 15 22:27:24 UTC 2021


On 11/15/21 1:58 PM, WebFreak001 wrote:
 > 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.
I don't see how it solves the problem. Sebastiaan Koppe might have 
intended to allocate the object dynamically with 'new' as well?

import std.stdio;

@safe:

struct ByChunk {
   FileReader* r;

   ~this() {
     writeln(__FUNCTION__);
   }

   void popFront() {
     writeln("popFront on ", r);
   }
}

struct FileReader {
   ~this() {
     writeln(__FUNCTION__, " on ", &this);
   }

   ByChunk byChunk() return scope {
     return ByChunk(&this);
   }
}

void main() {
   ByChunk helper;
   {
     auto file = new FileReader();  // <-- NOTE new
     helper = file.byChunk;
   }
   writeln("back in main");
   helper.popFront;
}

This is the current output:

deneme.ByChunk.~this
back in main
popFront on 7F12B377E000
deneme.ByChunk.~this
deneme.FileReader.~this on 7F12B377E000

But without that 'new', FileReader is destroyed before popFront:

deneme.ByChunk.~this
deneme.FileReader.~this on 7FFD8231D4B8   <-- BAD
back in main
popFront on 7FFD8231D4B8
deneme.ByChunk.~this

I think I am misunderstanding something here. :)

Ali



More information about the Digitalmars-d-learn mailing list