Program size, linking matter, and static this()
Jonathan M Davis
jmdavisProg at gmx.com
Sat Dec 17 18:05:41 PST 2011
On Saturday, December 17, 2011 13:20:33 Andrei Alexandrescu wrote:
> On 12/17/11 6:34 AM, so wrote:
> > If you are using singleton in your C++/D (or any other M-P language)
> > code, do yourself a favor and trash that book you learned it from.
> >
> > ---
> > class A {
> > static A make();
> > }
> >
> > class B;
> > B makeB();
> > ---
> >
> > What A.make can do makeB can not? (Other than creating objects of two
> > different types :P )
>
> Singleton has two benefits. One, you can't accidentally create more than
> one instance. The second, which is often overlooked, is that you still
> benefit of polymorphism (as opposed to making its state global).
Yes. There are occasions when singleton is very useful and makes perfect
sense. There's every possibity that it's a design pattern which is overused,
and if you don't need it, you probably shouldn't use it, but there _are_ cases
where it's useful.
In the case of std.datetime, the UTC and LocalTime classes are singletons
because there's absolutely no point in ever allocating multiple of them. It
would be a waste of memory. Imagine if
auto time = Clock.currTime();
had to allocate a LocalTime object every time. That's a lot of useless heap
allocation. By making it a singleton, it's far more efficient. Currently, it
does _no_ heap allocation, and once the singleton becomes lazy, it'll only
allocate on the first call. I don't see a valid reason _not_ to use a singleton
in this case - certainly not as long as time zones are classes, and I think
that they make the most sense as classes considering what they have to do and
how they have to behave.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list