DIP1000: Scoped Pointers

Rory McGuire via Digitalmars-d-announce digitalmars-d-announce at puremagic.com
Mon Aug 15 13:17:16 PDT 2016


On Mon, Aug 15, 2016 at 4:05 PM, Dicebot via Digitalmars-d-announce <
digitalmars-d-announce at puremagic.com> wrote:

> On 08/15/2016 04:54 PM, Rory McGuire via Digitalmars-d-announce wrote:
> > okay nice, so that code would not compile but code such as:
> > void test() {
> > scope rnd  = new Rnd; // reference semantic and stack allocated
> > auto rnd2 = rnd;
> >         some_sneaky_function_that_saves_global_state(rnd);
> > }
> > would still not be checked. And would crash inexplicably at the point
> > the global was accessed?
>
> some_sneaky_function_that_saves_global_state would have to be declared
> as `some_sneaky_function_that_saves_global_state(scope Rnd rnd)` to be
> allowed to use rnd as argument which prevents escaping to globals.
>
> What would still be the problem is if `Rnd` contains reference to
> another class internally (which gets manually destroyed when Rnd is
> destroyed) and `some_sneaky_function_that_saves_global_state` saves it
> instead - because by current design `scope` is a storage class and not
> transitive.
>
>
Thanks! That is an excellent explanation. Is the below a test case for that?

import std.stdio;

class Rnd {
NormalRefSemantics inner; // protecting this is irrelevant in more complex
objects?
this() {
inner = new NormalRefSemantics();
writeln("created");
}
~this() {
delete inner;// this is what causes the segfault
writeln("destroyed");
}

int i;
}

void test() {
scope rnd  = new Rnd; // reference semantic and stack allocated
auto rnd2 = rnd;

rnd.i = 2;
assert(rnd2.i == 2);
sneaky_escape(rnd);
}

void main() {
writeln("start test");
test();
writeln("test exited", oops);
}

class NormalRefSemantics {
this() {
writeln("I'm alive");
}
~this() {
writeln("inner destruction");
}
}
NormalRefSemantics oops;
void sneaky_escape(Rnd r) {
oops = r.inner; // how can we protect this inner part of the class from
escaping?
// would we need to mark classes and functions as "scope safe"? (similar to
"thread safe")
}

==
This DIP is really interesting, reminds me of back when we were playing
around with "emplace".

R
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-announce/attachments/20160815/f1828776/attachment.html>


More information about the Digitalmars-d-announce mailing list