scope
Part of KeywordsCategory
Description
This example shows how scope objects differ from non-scope objects. Note how the auto objects are destroyed as soon as they go out of scope. (This example is based on the older AutoExample example.)
Example
import std.stdio : writefln; class A { private char[] name; char[] toString() { return name; } this(char[] s) { name = s; writefln("%s created", name); } ~this() { writefln("%s destroyed", name); } } void test2() { scope A a2 = new A("test2"); } void test3() { A a3 = new A("test3"); } void test4() { scope A a4 = new A("test4"); } void main() { A a = new A("main test"); writefln("\tbegin main body"); test2(); test3(); test4(); writefln("\tend main body (garbage collector will run next...)"); }
Sample Batch File
@echo off set pgm=RaiiScopeExample dmd %pgm%.d %pgm%.exe pause erase %pgm%.obj erase %pgm%.map
Console Output
main test created
begin main body
test2 created
test2 destroyed
test3 created
test4 created
test4 destroyed
end main body (garbage collector will run next...)
test3 destroyed
main test destroyed
Compatibility
- Requires DMD 0.174 or later.
- Tested with DMD 0.174 on Windows 2000.
