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/[email protected]?page=5


Reply via email to