Make sure lifetime of helper structs is less than owning struct

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Nov 15 16:19:47 UTC 2021


On Mon, Nov 15, 2021 at 03:56:57PM +0000, WebFreak001 via Digitalmars-d-learn wrote:
> I have an API with some struct like a file reader. I want to add
> byChunks-like functionality to it, so I'm trying to implement it with
> a helper struct that implements opApply. I have disabled copying the
> file reader struct because it cleans up the resources once it goes out
> of scope, however now I need to temporarily save the resources in the
> helper struct to be able to read from it.
> 
> How can I make sure that the foreach helper struct (and with that the
> copies of the resources) cannot be used once the owning struct goes
> out of scope?
> 
> ```d
> ByChunk helper;
> {
>     auto file = FileReader(x);
>     helper = file.byChunk;
> }
> helper.popFront; // crash - I want the compiler to disallow this
> ```
> 
> is this currently possible or maybe possible with DIP1000?

What about make ByChunk do the construction of the File in its ctor
instead?  The problem with constructing it separately is that you can't
tie the two lifetimes together.  But if you create the File while
initializing the object, you ensure that the two lifetimes are tied
together, and with @disable this() you can make sure that ByChunk is not
constructible unless the code that opens the File also runs.


T

-- 
Computers shouldn't beep through the keyhole.


More information about the Digitalmars-d-learn mailing list