January 23, 2011 Re: How to use structs for RAII? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Sean Eskapp | On 2011-01-23 00:03, Sean Eskapp wrote: > It was recommended to me to use structs for RAII instead of scope classes, > since scope is being removed (?). However, since default-constructors for > structs can't exist, how does one do this? You can use a static opCall, like this: struct Foo { static Foo opCall () { Foo foo; // initialize foo return foo; } } auto foo = Foo(); -- /Jacob Carlborg |
January 23, 2011 Re: How to use structs for RAII? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Andrej Mitrovic | On 2011-01-23 01:14, Andrej Mitrovic wrote: > A workaround: > > import std.stdio; > import std.exception; > > struct A > { > int x; > > this(void* none) > { > if (none !is null) > { > enforce(0, "Tried to pass a parameter to A's constructor"); > } > > writeln("in constructor"); > // construction from here.. > x = 5; > } > } > > void main() > { > auto a = A(null); > } > > I think that would be safe, and closest to a "default" constructor. A static opCall would be better. See my answer to the original post. -- /Jacob Carlborg |
January 23, 2011 Re: How to use structs for RAII? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jacob Carlborg | Ah, I keep forgetting about opCall. Nice tips there. |
Copyright © 1999-2021 by the D Language Foundation