Singleton Pattern with struct
Artur Skawina
art.08.09 at gmail.com
Thu Jan 24 09:53:23 PST 2013
On 01/24/13 18:35, ParticlePeter wrote:
> On Thursday, 24 January 2013 at 17:21:38 UTC, Artur Skawina wrote:
>> On 01/24/13 17:52, ParticlePeter wrote:
>>> Why is the s inside the struct and another_s not identical ?
>>> Afaik that is the purpose of the ref keyword ?
>>
>> There currently are no reference variables in D [1]; the only way to get
>> a reference to something is via function arguments (including implicit
>> method ones) and function returns. So assigning a ref-return means a copy.
>>
>> You can workaround it like this:
>>
>> struct Singleton {
>> private:
>> this( int a = 0 ) {} ;
>> static Singleton* s ;
>>
>> public:
>> @disable this();
>> @disable this(this);
>> static instance() @property {
>> static struct Ref(T) { T* obj; ref g() @property { return *obj; } alias g this; @disable this(this); }
>> if ( s is null )
>> s = new Singleton( 0 ) ;
>> return Ref!(typeof(this))(s) ;
>> }
>>
>> int val = 0 ;
>> }
> Well ... I think I as well would not wanna do it like this, thanks :-)
> I'm fine with returning and using a pointer, fortunately there is no difference in syntax as in c, so it doesn't matter.
Careful, at some point you'll end up doing s[1] etc, and /then/ it matters.
The Ref struct is actually the way to deal with "ref" types in D; what I meant
by 'that's not how I'd do it' is that it might be better to use a global
(well, thread-local module-field in D) etc.
artur
More information about the Digitalmars-d-learn
mailing list