Encapsulate return value in scoped
Yuxuan Shui via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jun 11 02:01:04 PDT 2015
On Thursday, 11 June 2015 at 08:48:22 UTC, Yuxuan Shui wrote:
> Is there a way to encapsulate return value into scoped?
>
> Say I have a function that returns a new object:
>
> X new_x(T t...) {
> //Super complex input processing
> return new X(something);
> }
>
> And I want to encapsulate the result using scoped, is that
> possible? Can I just do:
> return scoped!X(something).
> ?
>
> If I understand correctly, the data will be blitted, but the
> destructor will be called, so the returned object will be in
> invalid state.
It's even weirder than I thought, this:
import std.stdio,
std.typecons;
class A {
int b;
~this() {
writeln("Des");
}
this(int x) {
b=x;
writeln("Cons");
}
}
auto x() {
A x = scoped!A(10);
writeln(x.b);
writeln("Return x");
return x;
}
void main() {
auto tx = x();
writeln("Return main");
}
Produce output:
Cons
Des
0
Return x
Return main
Which I totally don't understand.
More information about the Digitalmars-d-learn
mailing list