Singleton in Action?
Alex
sascha.orlov at gmail.com
Mon Feb 4 10:58:31 UTC 2019
On Monday, 4 February 2019 at 10:36:49 UTC, Ron Tarrant wrote:
> On Sunday, 3 February 2019 at 18:53:10 UTC, Jacob Carlborg
> wrote:
>
>> You don't need to make it so complicated. Here's a simpler
>> example:
>
> Excellent. Thank you. Simple is best.
>
>
>> private __gshared auto instance_ = new DSingleton;
>
> My understanding is that in D, this line effectively says: the
> singleton is created at compile time and can't be changed,
> ever. Is that a fair assessment?
>
No, it can.
´´´
class DSingleton
{
private __gshared auto instance_ = new DSingleton;
size_t state;
private this(){} // private to make sure no one else can
create an instance
static DSingleton instance() { return instance_; }
}
void main()
{
assert(DSingleton.instance.state == 0);
DSingleton.instance.state = 5;
assert(DSingleton.instance.state == 5);
}
´´´
>>
>> private this() // private to make sure no one else can
>> create an instance
>
> I've seen comments similar to this in several examples. When
> you say "no one else" you're personifying callers?
To some extent...
> And so this means: No caller outside the object? Which really
> amounts to: Since no one INside the object WILL call this() and
> no one OUTside CAN call this(), it won't ever get called.
I think, what is meant is: The class has to be placed alone in a
module so that no one outside the class (and the module) has any
direct access to object creation routine.
>
>
>> writeln(DSingleton.instance);
>
> No '()' needed for the call to DSingleton.instance?
>
> If it's called again from somewhere else, say from within an
> object function several levels of scope away, it's called the
> same way?
Yes. https://dlang.org/spec/function.html#optional-parenthesis
More information about the Digitalmars-d-learn
mailing list