resource structs and default constuction
Erik Smith via Digitalmars-d
digitalmars-d at puremagic.com
Mon Jun 1 09:00:19 PDT 2015
I have a struct that uses RefCounted internally to manage a
database environment. It’s basically in the same boat as
RefCounted itself in that it requires runtime construction. Two
things set it apart:
1) No-arg construction is required
2) The potential prevalence of this type in application code and
getting default initialized by mistake.
This issue has been discussed before (see link below). It would
be nice if this could be addressed in the language at some point,
but as far as I can tell, the best option I have now is to put
version(assert) checks in all of my member functions to check for
proper construction.
For the default construction issue, a factory function was
suggested as an option. I came up with the following approach:
struct Database {
static Database create() {
return Database("");
}
static Database create(A...)(auto ref A args) {
return Database(args);
}
this(string uri) {…}
this(Config config) {…}
...
}
The first static function provides a way to default construct.
The 2nd static function provide uniformity with all of the other
constructors that might be present.
Might this be a good idiom to apply for resource managing structs
in general?
erik
previous forum discussion on default constructors:
http://forum.dlang.org/thread/fgldbozuneoldxjrwxje@forum.dlang.org?page=5
More information about the Digitalmars-d
mailing list