Extending the lifetime of scope objects
    Ali Çehreli 
    acehreli at yahoo.com
       
    Tue Jul 20 12:54:45 PDT 2010
    
    
  
What are all the cases that extend the lifetime of scoped objects?
Binding a delegate to a scope object extends the lifetime of that 
object, which would normally end upon exiting that scope. The lifetime 
of i is extended here:
int delegate(int) make_delegate()
{
     int i;    // lives as long as the returned delegate lives
     return (int param) {
         return i + param;         // uses i
     };
}
void main()
{
     auto del = make_delegate();
     del(42);                      // uses i
}
I was surprised to discover that, the same does not apply to struct 
objects, *if* the struct has a destructor:
struct S
{
     int i;
     ~this()  // prevents life extension
     {}
}
int delegate(int) make_delegate()
{
     auto s = S();
     return (int param) {
         return s.i + param;
     };
}
void main()
{
     auto del = make_delegate();
     del(42);
}
Error: variable deneme.make_delegate.s has scoped destruction, cannot 
build closure
Are the "life extending" cases short and simple? What are they? :)
Thank you,
Ali
    
    
More information about the Digitalmars-d-learn
mailing list