View mode: basic / threaded / horizontal-split · Log in · Help
October 14, 2008
scope and raising from constructor
Hi all,
I've posted this on D learn, just to know: is it a bug? If yes, I'll post a ticket...
If not, I don't understand the difference behaviour...
Thanks, Paolo

module tests.d.scopes.t02.test;

class Resource {
   static int allocated = 0;
   this( bool mustThrow = false ){
       allocated ++;
       if( mustThrow ) throw new Exception("bang");
   }
   ~this(){
       allocated --;
   }
}
class Factory {
   Resource resource(bool b=false){
       return new Resource(b);
   }
}

import std.gc, std.stdio;
void main(){
   // In this case everything it's ok
   {
       try {
           scope r1 = new Resource(true);
           assert( false );
       }
       catch(Exception e){}
       assert( Resource.allocated == 1);
       std.gc.fullCollect();
       assert( Resource.allocated == 1 );
   }
   
   Resource.allocated = 0;
   
   // In this case the destructor IS called, only on collect...
   {
       auto f = new Factory();
       try {
           scope r1 = f.resource(true);
           assert( false );
       }
       catch(Exception e){}
       assert( Resource.allocated == 1);
       std.gc.fullCollect();
       assert( Resource.allocated == 0 ); // Dho! Destructor called!
   }
}
October 14, 2008
Re: scope and raising from constructor
On Tue, 14 Oct 2008 11:51:27 +0400, Paolo Invernizzi  
<arathorn@fastwebnet.it> wrote:

> Hi all,
> I've posted this on D learn, just to know: is it a bug? If yes, I'll  
> post a ticket...
> If not, I don't understand the difference behaviour...
> Thanks, Paolo
>
> module tests.d.scopes.t02.test;
>
> class Resource {
>     static int allocated = 0;
>     this( bool mustThrow = false ){
>         allocated ++;
>         if( mustThrow ) throw new Exception("bang");
>     }
>     ~this(){
>         allocated --;
>     }
> }
> class Factory {
>     Resource resource(bool b=false){
>         return new Resource(b);
>     }
> }
>
> import std.gc, std.stdio;
> void main(){
>     // In this case everything it's ok
>     {
>         try {
>             scope r1 = new Resource(true);
>             assert( false );
>         }
>         catch(Exception e){}
>         assert( Resource.allocated == 1);
>         std.gc.fullCollect();
>         assert( Resource.allocated == 1 );
>     }
>    Resource.allocated = 0;
>    // In this case the destructor IS called, only on collect...
>     {
>         auto f = new Factory();
>         try {
>             scope r1 = f.resource(true);
>             assert( false );
>         }
>         catch(Exception e){}
>         assert( Resource.allocated == 1);
>         std.gc.fullCollect();
>         assert( Resource.allocated == 0 ); // Dho! Destructor called!
>     }
> }

I think there is no need to post it twice across different newsgroups,  
most of the people monitor all or none of them.
Top | Discussion index | About this forum | D home