How to use structs for RAII?
Jonathan M Davis
jmdavisProg at gmx.com
Sat Jan 22 21:41:42 PST 2011
On Saturday 22 January 2011 15:09:29 bearophile wrote:
> Sean Eskapp:
> > 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?
>
> Inside the ~this() you may put code, to deallocate resources you have
> allocated in an explicit constructor (or in some creation method). Is this
> enough?
The typical thing to do when you want a default constructor for a struct is to
use a static opCall(). Then, for struct S, you'd do
auto s = S();
If you did S s(), it still wouldn't work, so you might want to add an assertion
in the destructor which verifes that the struct wasn't constructor with S.init,
in which case what the destructor would be doing would likely be wrong.
Personally, I _always_ declare struct variables in this form
auto s = S();
and never as
S s();
It avoids most of the problem with a struct's init value. But you can still get
structs initialized to their init when they're in arrays and the like (which is
a good part of the reason that init exists in the first place).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list