resource structs and default constuction
Jonathan M Davis via Digitalmars-d
digitalmars-d at puremagic.com
Mon Jun 1 12:04:17 PDT 2015
On Monday, 1 June 2015 at 16:00:20 UTC, Erik Smith wrote:
> 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
If you want to force that a constructor be called rather than
using the init value, then you need to make the init value
unusable by @disabling this(). Then the caller _has_ to
explicitly call a constructor or factory function. Regardless, if
you want a constructor that takes no arguments for a struct, you
need a factory function, since you can't have struct constructors
with no parameters.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list