Scope and with

Ali Çehreli acehreli at yahoo.com
Wed Jan 23 08:37:58 PST 2013


On 01/23/2013 01:52 AM, Namespace wrote:

 > int* mem = cast(int*) malloc(10 * int.sizeof);
 > scope(exit) free(mem);
 >
 > After leaving scope the memory is freed.
 > Otherwise you have to write 'free(mem)' at the end of the scope and
 > thats a thing that I forget sometimes in C.

Yes, the correctness of code in C depends on remembering to do so and 
also being disciplined to follow a certain function design style. (All 
resources are released in the 'finally' area of the function.)

On the other hand, putting free(mem) at the end of a scope is a coding 
error in any language that has exceptions. (The exceptions of this rule 
are special lines of code where no exception can be thrown.) That's why 
RAII is an essential idiom in C++. 'scope' is a welcome addition to D 
that obviates the need for little RAII classes in some cases.

To the OP, here is a chapter on scope:

   http://ddili.org/ders/d.en/scope.html

That chapter contains references to the previous chapter, which is about 
exceptions:

   http://ddili.org/ders/d.en/exceptions.html

Ali



More information about the Digitalmars-d-learn mailing list