饿汉模式(线程安全)

    1. class singleton
    2. {
    3. protected:
    4. singleton()
    5. {}
    6. private:
    7. static singleton* p;
    8. public:
    9. static singleton* initance();
    10. void sayhi() {std::cout << "Hi!" << std::endl;}
    11. };
    12. singleton* singleton::p = new singleton;
    13. singleton* singleton::initance()
    14. {
    15. return p;
    16. }
    17. int main(int argc, char* argv[]) {
    18. singleton::initance()->sayhi();
    19. }

    懒汉模式 (c++11保证线程安全)

    1. class S
    2. {
    3. public:
    4. static S& getInstance()
    5. {
    6. static S instance; // Guaranteed to be destroyed.
    7. // Instantiated on first use.
    8. return instance;
    9. }
    10. private:
    11. S() {} // Constructor? (the {} brackets) are needed here.
    12. // C++ 03
    13. // ========
    14. // Don't forget to declare these two. You want to make sure they
    15. // are unacceptable otherwise you may accidentally get copies of
    16. // your singleton appearing.
    17. S(S const&); // Don't Implement
    18. void operator=(S const&); // Don't implement
    19. // C++ 11
    20. // =======
    21. // We can use the better technique of deleting the methods
    22. // we don't want.
    23. public:
    24. S(S const&) = delete;
    25. void operator=(S const&) = delete;
    26. // Note: Scott Meyers mentions in his Effective Modern
    27. // C++ book, that deleted functions should generally
    28. // be public as it results in better error messages
    29. // due to the compilers behavior to check accessibility
    30. // before deleted status
    31. };

    全局变量析构问题

    1. class A
    2. {
    3. public:
    4. // Get the global instance abc
    5. static A& getInstance_abc() // return a reference
    6. {
    7. static A instance_abc;
    8. return instance_abc;
    9. }
    10. };
    11. class B
    12. {
    13. public:
    14. static B& getInstance_Bglob;
    15. {
    16. static B instance_Bglob;
    17. return instance_Bglob;;
    18. }
    19. ~B()
    20. {
    21. A::getInstance_abc().doSomthing();
    22. // The object abc is accessed from the destructor.
    23. // Potential problem.
    24. // You must guarantee that abc is destroyed after this object.
    25. // To guarantee this you must make sure it is constructed first.
    26. // To do this just access the object from the constructor.
    27. }
    28. B()
    29. {
    30. A::getInstance_abc();
    31. // abc is now fully constructed.
    32. // This means it was constructed before this object.
    33. // This means it will be destroyed after this object.
    34. // This means it is safe to use from the destructor.
    35. }
    36. };

    参考
    https://www.cnblogs.com/qiaoconglovelife/p/5851163.html
    https://stackoverflow.com/questions/1008019/c-singleton-design-pattern
    https://stackoverflow.com/questions/335369/finding-c-static-initialization-order-problems/335746#335746