[Dlang-internal] DIP1000 discussion and testing: RC pointer snippet
Dicebot via Dlang-internal
dlang-internal at puremagic.com
Sun Oct 16 06:55:58 PDT 2016
On 10/16/2016 04:45 PM, Dicebot wrote:
> I'll start separate sub-threads with more details.
This snippet is a variation of RCSlice example from the DIP:
------------------------------------------------------------
@safe unittest
{
@safe static struct RCPointer (T)
{
private T* payload;
private size_t* count;
this (T initializer)
{
this.payload = new T;
*this.payload = initializer;
this.count = new size_t;
*count = 1;
}
this (this)
{
if (this.count)
++(*this.count);
}
@trusted ~this ()
{
if (this.count && !--(*this.count))
{
delete payload;
delete count;
}
}
// must bind lifetime of return value to lifetime of `this`
T* get () return scope
{
return this.payload;
}
alias get this;
}
auto ptr = RCPointer!int(42);
auto leak2 = ptr.get(); // must not compile unless spec says 'auto'
// can deduce scope
int* leak1 = ptr.get(); // must not compile
void foo (RCPointer!int)
{
assert(*(ptr.count) == 2);
}
foo(ptr);
void bar (ref int)
{
assert(*(ptr.count) == 1);
}
bar(*ptr);
}
------------------------------------------------------------
DIP1000 says that `return scope` applied to a method means applying it
to aggregate `this`. It also says that struct is viewed as a composition
of all its fields when it comes to lifetime.
Natural consequence is that it should be possible to define `get` method
like in this example to ensure that pointer won't outlive struct
instance it came from.
This snippet currently compiles, failing to reject both "leak" lines.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 455 bytes
Desc: OpenPGP digital signature
URL: <http://lists.puremagic.com/pipermail/dlang-internal/attachments/20161016/c8961b7f/attachment-0002.sig>
More information about the Dlang-internal
mailing list