Re: Singletons: can they be ultra-safe?
neelsmail@rediffmail.com wrote:
This is one of the questions asked to me and I wanted your opinion
about it. Following is the scenario -
A *x = A::Instance() // A is a singleton class, with thread safty
implemented.
A *y = x;
First mistake here IMHO:
1. You are passing a pointer to the caller. This pointer could be zero, what
would that mean? If it can't be zero, return a reference and throw when
something keeps you from doing that.
2. Who owns what this points to? With a reference, it is much clearer that
you are only an inspector of the given object, same with a shared_ptr<A>.
In both cases, it is pretty clear that this code:
Now, from here x is given to one thread and y to another:
Thread function body of A:
{
x->DoSomething();
delete x;
}
is buggy. If it was a reference, you would have to do 'delete &x', which
probably nobody that knows C++ basics will do, with a shared_ptr you do
nothing which also achieves the goal.
Question: Is there anything you (a prgrammer) can do to make it safer?
Yes, don't use raw pointers in an undocumented and unsafe way as above.
My Answer: Short answer is "No". Of course I can add reference
counting and only if reference count reaches 0 I will delete the
object (override operator delete).
This has nothing to do with overriding operator delete!
But, there is nothing a programmer can do that is implicit/compulsory
that will avoid the crash.
I think the problem with the code you have shown is unclear ownership
issues. For a singleton that is shared by several places in the code, a
reference-counted approach (either via an explicitly maintained refcounter
or by counting them on demand with a garbage collector) is a sure way to
avoid dangling references or resource leaks. In other cases an object as a
whole is passed along (ownership is transferred from one point to the other
but not shared), in that case std::auto_ptr comes in handy.
Uli
--
Sator Laser GmbH
Gesch??ftsf??hrer: Ronald Boers, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]