On Thu, 01 Sep 2011 13:31:29 -0400, Nick Sabalausky <[email protected]> wrote:

You could do something like this:

class AClass
{
   int a = 10;
}

struct AStruct
{
// Never use this directly, except inside the "aclass" property functions
   private AClass _aclass;

    @property AClass aclass()
    {
        if(_aclass is null)
            _aclass = new AClass();
        return _aclass;
    }

    @property void aclass(AClass c)
    {
        _aclass = c;
    }
}

-------------------------------
Not sent from an iPhone.

This doesn't work.  It has the same problem as AA's currently do:

foo(AStruct str)
{
  str.aclass.a = 5;
}

void main()
{
   AStruct str;
   // assert(str.aclass.a == 10);
   foo(str);
assert(str.aclass.a == 5); // fails unless you comment out the line above.
}

And to answer the OP's question, the easiest thing to do is create a constructor function (not a ctor, because you can't have default ctors). Yes, it's annoying, but it's about as close as you can get to C++.

struct AStruct
{
   static AStruct create() {return AStruct(new AClass());}
}

auto str = AStruct.create();

Until the next release, there is no way to force a user to always call such a function. The next relase allows @disable this(), which should disable simply declaring a struct.

This is an alternative to Timon's opCall solution.

-Steve

Reply via email to