Scope statement

Simen Kjaeraas simen.kjaras at gmail.com
Tue Feb 5 15:48:05 PST 2008


Lars V <nospamplease at nospam.com> wrote:

> Bill Baxter Wrote:
>
>> Lars V wrote:
>> > Hi,
>> >
>> > I have a question:
>> >
>> > void foo()
>> > {
>> >   Obj o = new Obj();
>> > }
>> >
>> > In this code, the destructor of the object will be called ALWAYS at  
>> the end of the function?
>> >
>> > In D, the objects are not destroyed when they go out of their  
>> scopes??? Is necessary to use the "scope" statement?
>> >
>> > I really don't understand the necessity of the scope statement...  
>> could anybody explain it?
>>
>> Yes you need to use scope if you want deterministic destruction.
>>
>> Allocation and deallocation are expensive, and one of the nice things
>> about a garbage collection system is that it lets you do clean-up more
>> lazily.  That way you can handle a bunch of de-allocations at once.
>> Think of it as waiting a week to vacuum up the room instead of pulling
>> out the vacuum cleaner every time a piece of dust hits the floor.
>>
>> --bb
>
>
> But, when the function ends the object should be collected by the GC  
> (there are no more references to it) and the GC will call the  
> destructor, no? I don't understand it.
>

When the object goes out of scope, there are no more pointers to it,  
correct. This only means however, that the next time the GC runs a  
collection cycle (which might be right after you've exited the scope, but  
you can't know that), the object's destructor will be called.

If you instead use
void foo()
{
	scope Obj o = new Obj();
}

You are guaranteed that the moment the object goes out of scope, its  
destructor will be called.

-Simen


More information about the Digitalmars-d-learn mailing list