Encapsulate return value in scoped

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 11 14:38:58 PDT 2015


On 06/11/2015 12:51 PM, Yuxuan Shui wrote:
 > On Thursday, 11 June 2015 at 19:23:49 UTC, Ali Çehreli wrote:

 >>   http://ddili.org/ders/d.en/destroy.html#ix_destroy.scoped
 >>
 >> This issue is explained at the end of that section.
 >>
 >> Ali
 >
 > 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



More information about the Digitalmars-d-learn mailing list