Encapsulate return value in scoped

Yuxuan Shui via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 18 16:53:36 PDT 2015


On Thursday, 11 June 2015 at 21:38:59 UTC, Ali Çehreli wrote:
> On 06/11/2015 12:51 PM, Yuxuan Shui wrote:
> > On Thursday, 11 June 2015 at 19:23:49 UTC, Ali Çehreli wrote:
>
> >> [...]
> >
> > Can you explain more about why the destructor is not called
> when
> > returning a struct?
>
> Are you asking in general or specific to scoped!C?
>
> In general, D has move semantics built into the language. It 
> depends on whether the returned expression is an rvalue or an 
> lvalue: rvalues are moved, lvalues are copied. And the 
> destructor will not be called for a moved object.
>
> About returning scoped!C, I think it works:
>
> import std.stdio;
> import std.typecons;
>
> class C
> {
>     ~this()
>     {
>         writeln("dtor");
>     }
> }
>
> auto foo()
> {
>     auto c = scoped!C();
>     return c;
> }
>
> void main()
> {
>     writeln("entering scope");
>     {
>         writeln("calling");
>         auto s = foo();
>         writeln("returned");
>     }
>     writeln("leaving scope");
> }
>
> "dtor" is printed upon leaving the scope:
>
> entering scope
> calling
> returned
> dtor
> leaving scope
>
> Ali

I just find out that the document of scoped says that "It's 
illegal to move a class instance even if you are sure there are 
no pointers to it. As such, it is illegal to move a scoped 
object."

So this is not a solution?


More information about the Digitalmars-d-learn mailing list