Struct no-arg constructor?

Jonathan M Davis jmdavisProg at gmx.com
Wed Jul 25 02:51:04 PDT 2012


On Wednesday, July 25, 2012 11:34:12 monarch_dodra wrote:
> According to TDPL, the rationale for structs not having default
> constructors is "T.init", were T.init is defined as:
> *A static, known at compile time, mem-copyable value.
> *The value that gets mem-copied into structs before the
> constructors are called
> *The value that gets mem-copied into structs when moving stuff
> out of them.
> **Destructors must support being called on a T.init element.
> 
> The thing is, I can't, for the life of me, understand how that
> interferes with having a default constructor. Wouldn't keeping
> the current definition of init, but allowing a call to a "no-arg"
> constructor after after the mem-copy of T.init also work? As long
> as the destructor keeps supporting calls to T.init objects, then
> all is fine. Why hold out on a very useful functionality?
> 
> Am I missing a case where having a default constructor could
> actually mess things up? The restriction just feels gratuitous
> for me.

If you want to be able to do S(), then declare a static opCall for S which 
returns an S constructed in the way that you want.

struct S
{
    static S opCall()
    {
        //do whatever you do
        return s;
    }
}

auto s = S();

but

S s;

will always be init. But you can't have a default constructor, because then it 
conflicts with what init would be doing. e.g. would

S s;

be initialized with init or with the default constructor? But the static 
opCall does let you construct a struct without any arguments. You just can't 
have anything which isn't explicitly constructed using a default constructor, 
because that's init's job.

Also, because all types must have an init value, if you can't guarantee that 
your struct is valid and usable with its init property, then you'll either 
have to disable the struct's init value so that it cannot be use

struct S
{
    @disable this();
}

or you'll have to live with the fact that using it could blow up in your face 
- which really isn't all that different from other types (e.g. float.init is NAN 
and pointers default to null).

- Jonathan M Davis


More information about the Digitalmars-d mailing list