`return ref`, DIP25, and struct/class lifetimes
Joseph Rushton Wakeling via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon May 16 06:49:35 PDT 2016
Hello all,
Consider a struct that wraps a pointer to some other piece of
data as follows:
struct MyWrapper(T)
{
private T* data;
public this(ref T input)
{
this.data = &input;
}
... other methods that use `this.data` ...
}
Is there any way to guarantee at compile time that the input data
will outlive the wrapper struct?
I'd assumed (dangerous thing to do...) that DIP25 would allow
this to be guaranteed by `return ref`, but compiling/running the
following program, with or without the --dip25 flag, would appear
to suggest otherwise:
////////////////////////////////////////////////////////////
struct MyWrapper(T)
{
private T* data;
public this(return ref T input)
{
this.data = &input;
}
public T get() return
{
return *(this.data);
}
invariant()
{
assert(this.data !is null);
}
}
auto badWrapper()
{
double x = 5.0;
return MyWrapper!double(x);
}
void main()
{
import std.stdio;
auto badWrap = badWrapper();
writeln(badWrap.get());
}
////////////////////////////////////////////////////////////
Is there any current way to achieve what I'm looking for here, or
is this all on a hiding to nothing? :-(
N.B. for motivation behind this request, see:
https://github.com/WebDrake/dxorshift/pull/1
More information about the Digitalmars-d-learn
mailing list