Search code examples
c++singletonlinkage

C++ singleton lazy initialization implementation and linkage seems conflict


C++ Singleton design pattern I come across this question and learned that there are two ways to implement the singleton pattern in c++.

1) allocate the single instance in heap and return it in the instance() call

2) return a static instance in the instance() call, this is also known as the lazy initialization implementation.

But I think the second, that is the lazy initialization implementation, is wrong due to following reasons. Static object returned from the instance() call has internal linkage and will have unique copies in different translation unit. So if user modifies the singleton, it will not be reflected in any other translation unit.

But there are many statement that the second implementation is correct, am I missing something?


Solution

  • You are wrong, because the singleton is defined in one single translation unit, the one that contains the definition of the function that returns it. That means that all translation units that wants to use the singleton ask it to the single one that actually defines it, and in the end all use the same object (as expected for a singleton pattern :-) ).