Re: Confused about a thread-safe singleton example.
On Dec 3, 4:59 pm, Noah Roberts <u...@example.net> wrote:
Maxim Yegorushkin wrote:
On Dec 3, 9:43 am, James Kanze <james.ka...@gmail.com> wrote:
1. Don't use singletons. Ever. Pretty much all of the value
of the GoF Design Patterns book is negated by the fact that
they chose to legitimize Singleton as a design pattern.
Singleton is just a fancy name for global variable. We should
call it the Global Variable (anti)Pattern.
And there are valid reasons for using it.
What are those reasons?
Some things must be inherently unique in a process.
This is what global variables are for.
Globals do not offer any protection against further instantiation. If
something must be unique then it should only be possible to create a
single variable of that type. How are you going to offer that with an
unprotected variable, a comment saying, "Don't make any of these..."?
It looks like you are confusing types with variables. The ability to
create a variable of a particular type depends on that type only, not
whether there are variables of that type and whether those variables
are global or not.
Using abstract classes (interfaces) and global references you can
achieve the desired effect.
That method does not work.
[]
Here is a proof that it works. Example of a type you can't instantiate
and a global variable of that type:
// header.h begin
struct X
{
virtual void foo() = 0;
};
extern X& global_x;
// header.h end
// source.cc begin
#include "header.h"
namespace {
struct XImpl : X
{
void foo() {}
} x;
}
X& global_x = x;
// source.cc end
--
Max