1. #include <iostream>
    2. using namespace std;
    3. class Singleton {
    4. private:
    5. Singleton() {
    6. cout << "Constructor Called" << endl;
    7. }
    8. public:
    9. Singleton(Singleton &) = delete;
    10. Singleton &operator=(Singleton &) = delete;
    11. ~Singleton() {
    12. cout << "Destructor Called" << endl;
    13. }
    14. static Singleton &Instance() {
    15. // 注意返回引用
    16. // 使用local static对象替换non-local static对象
    17. static Singleton singleton;
    18. return singleton;
    19. }
    20. };
    21. int main() {
    22. cout << "main begin" << endl;
    23. Singleton &s1 = Singleton::Instance();
    24. cout << "1" << endl;
    25. Singleton &s2 = Singleton::Instance();
    26. cout << "2" << endl;
    27. Singleton &s3 = s1;
    28. cout << "main end" << endl;
    29. return 0;
    30. }

    输出
    image.png
    可见构造函数只调用了一次,并且local static的初始化是在第一次执行到其声明式时,生命周期维持到程序结束。

    并且该方法在c++11之后是线程安全的!!!

    If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. 如果当变量在初始化的时候,并发同时进入声明语句,并发线程将会阻塞等待初始化结束。