On Thursday, 24 January 2013 at 16:17:34 UTC, Era Scarecrow wrote:
On Thursday, 24 January 2013 at 16:07:36 UTC, Maxim Fomin wrote:
Yes, but this can be broken by:
void main()
{
Singleton s = * Singleton.instance;
printf( "%d\n", s.val ) ; //
Singleton.instance.val = 2 ;
printf( "%d\n", s.val ) ; //0
}
Here s is explicitly defined to be a struct object, not
pointer (reference), so main.s is independent of further
modification of Singleton.instance.
I'm not sure but this seems like one of the few appropriate
places i would just make a normal struct and just use a global
variable. True there could 'be' multiple instances of these
singletons, but only ever making one ensures it would work
right so long as you cannot copy it. Wasn't disabling
this(this) and opAssign the way to ensure that didn't happen?
Course if you didn't and you relied on the instance one, and
you cannot copy then you could only pass by reference or be
required to use .instance every time you needed it. Seems a bit
excessive.
Hmmm. You could separate the data and remove the pointer...
then use alias this.
[code]
struct Singleton {
static SingletonData single;
alias single this;
@disable this(this);
//disable copy/assignment? Not that it would matter...
//copying nothing does nothing, as there's nothing here.
private static struct SingletonData {
//methods and data here.
}
[/code]
I agree, but disabling ctors makes creating module-level object
tricky. Static struct initialization might help.