Create class on stack
Moritz Maxeiner via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Aug 7 06:40:18 PDT 2017
On Monday, 7 August 2017 at 10:50:21 UTC, Mike wrote:
> On Sunday, 6 August 2017 at 15:47:43 UTC, Moritz Maxeiner wrote:
>
>> If you use this option, do be aware that this feature has been
>> scheduled for future deprecation [1].
>> It's likely going to continue working for quite a while
>> (years), though.
>>
>> [1]
>> https://dlang.org/deprecate.html#scope%20for%20allocating%20classes%20on%20the%20stack
>
> FYI: http://forum.dlang.org/post/np1fll$ast$1@digitalmars.com
>
> "Yes, it will have to be updated - but I didn't want to adjust
> it before DIP1000 spec is finalized. Rationale that was driving
> deprecation of scope storage class is becoming obsolete with
> DIP1000 implemented but not before."
Thanks, I wasn't aware of this. I tried fooling around scope
classes and DIP1000 for a bit and was surprised that this is
allowed:
---
import core.stdc.stdio : printf;
import std.algorithm : move;
class A
{
int i;
this() @safe
{
i = 0;
}
}
void inc(scope A a) @safe
{
a.i += 1;
}
void print(scope A a) @trusted
{
printf("A@%x: %d\n", cast(void*) a, a.i);
}
auto makeA() @safe
{
scope a = new A();
a.print();
return move(a);
}
void main() @safe
{
auto a = makeA();
foreach (i; 0..10) {
a.print();
a.inc();
}
}
---
You can still create a (scope) class on the stack, escape a
reference to it using `move` and use it afterwards, all within
the rules of @safe, so I'm not convinced that the reason for
deprecating scoped classes is gone yet.
Compare this to `scoped`, which behaves as expected (since it
wraps the reference type object in a value type):
---
import std.typecons : scoped;
auto makeA() @trusted
{
auto a = scoped!A();
a.print();
return move(a);
}
void main() @trusted
{
auto a = makeA();
foreach (i; 0..10) {
a.print();
a.inc();
}
}
---
More information about the Digitalmars-d-learn
mailing list