wk****@yahoo.com a écrit :
Why aren't "Singletons" done like this in C++:
A.hpp:
class A
{
public: static A theA;
private:
A() { /* ... */ }
};
A.cpp:
A A::theA;
rather than the complicated approaches I've
seen with the instance being allocated with "new"?
Your approach is dangerous, as you don't know when the object is
created. You are only able to successfully use it after you entered in
main(), and you should not use it after main() exit. It means that your
singleton cannot be used in static object construction and so on - note
that this might not be a problem in the end.
Meyer's singleton (the getInstance() function declares a static
variable and returns this variable) was probably what you got in mind -
the standard ensures that the static is constructed the first time you
entered in the function, so it is always valid - until you quit main()
(static objects order of destruction is well defined, but not easily
handled from the programmer point of view, so you'd better not use it
after you exit main()). Allocating the instance using new() in the
getInstance() function allows the same use as Meyer's singleton, but
the singleton is still valid until the memory is freed. If it is never
freed then you singleton is always valid.
* Your approach
class A
{
private:
static A theA;
A() { }
~A() { }
A(const A&) { }
A& operator=(const A&);
public:
// time of construction is not known by the programmer
// time of destruction is not known by the programmer
A& instance() { return theA; }
};
* Meyer's approach
class A
{
private:
A() { }
~A() { }
A(const A&) { }
A& operator=(const A&);
public:
// the instance will be created when you enter the
// function for the first time
// time of destruction is hard to tell from the programmer
// point of view
A& instance() { static A a; return a; }
};
* GoF approach:
class A
{
private:
A() { }
~A() { }
A(const A&) { }
A& operator=(const A&);
public:
// the instance will be created when you enter the
// function for the first time
// the instance is never destroyed
A& instance() { static A *a = NULL; if (!a) a = new A(); return a; }
};
There's a very interesting discussion about singleton and their
possible implementation in the Modern C++ book of Andrei Alexandrescu.
Regards,
-- Emmanuel Deloget, Artware