Program size, linking matter, and static this()

Jakob Ovrum jakobovrum at gmail.com
Sat Dec 17 13:12:16 PST 2011


On Saturday, 17 December 2011 at 21:02:58 UTC, so wrote:
> On Sat, 17 Dec 2011 21:20:33 +0200, Andrei Alexandrescu
> <SeeWebsiteForEmail at erdani.org> 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).
>>
>> Andrei
>
> Now i am puzzled,
> "makeB" does both and does better. (better as it doesn't expose 
> any detail to user)

Both of your examples are the singleton pattern if `make` returns 
the same instance every time, and arguably (optionally?) A or B 
shouldn't be instantiable in any other way.

I suspect that the reason a static member function is prevalent 
is because it's easy to just make the constructor private (and 
not have to mess with things like C++'s `friend`). In D, there's 
no real difference because you can still use private members as 
long as you're in the same module.

The only difference between them I can see is that the 
module-level function doesn't expose the class name directly when 
using the function, which is but a minor improvement.


More information about the Digitalmars-d mailing list