struct and default constructor

ketmar via Digitalmars-d digitalmars-d at puremagic.com
Fri Oct 10 01:03:39 PDT 2014


On Fri, 10 Oct 2014 01:32:51 +0000
dcrepid via Digitalmars-d <digitalmars-d at puremagic.com> wrote:

> This seems like a language limitation to me.
that is what we have to pay for the rule "type must always has
well-defined initial value".

the thing is that struct must have initial value that can be calculated
without executing any code. i.e. `T.init`. with default struct
constructor we can't have such initial state anymore. this is highly
unsafe.

yet compiler ignores constructor with default args when creating
struct. i.e. for this:

  struct A {
    @disable this ();
    this (int v=42) { ... }
    ...
  }
  ...
  auto a = A();

compiler will not call this(42), but will generate error. i'm not sure
if this must be changed though, 'cause `this (int)` now becames default
constructor and we have no well-defined initial value anymore.

> So no possibility of using 
> objects as resource acquire/release mechanisms.
> I assume using scoped with class objects will have a similar 
> problem..
no, stack-allocated object is GC root, so anything it holds reference
to will not be destroyed until stack object is alive. so destructor of
stack-allocated object *can* be used for doing cleanup.

but you can use templates to build your "anchor" structs. it's hard to
say without concrete code samples.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20141010/14aecc3f/attachment.sig>


More information about the Digitalmars-d mailing list