Scope and with
simendsjo
simendsjo at gmail.com
Wed Jan 23 02:28:22 PST 2013
On Wednesday, 23 January 2013 at 09:52:40 UTC, Namespace wrote:
> On Wednesday, 23 January 2013 at 08:33:44 UTC, SaltySugar wrote:
>> Can someone explain me scope and with statements?
>
> with statements simplify the access to a class, struct or
> something else.
> For example:
> class A {
> public:
> int b = 42;
> }
>
> A a = new A();
> normal access:
> writeln(a.b); // writes 42
>
> with 'with':
>
> with (a) {
> writeln(b); // writes 42
> }
>
> scope is one of my favorite features. You can create scopes
> which are executed if the appropriate case comes.
> For example at the end of a scope, by success of a scope etc.
>
> Example:
> 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.
I often use with to initialize objects (as D doesn't have object
initializers as c#):
auto c = new C(); // some class
with(c) {
someProp = someValue; // instead of c.someProp
// etc
}
scope also has a different meaning if used in function parameters:
void f(scope C c) {
// not allowed to pass c anywhere - it's not allowed to leave
this scope
}
More information about the Digitalmars-d-learn
mailing list