Singleton Destructors

后端 未结 12 1714
一整个雨季
一整个雨季 2021-01-31 03:55

Should Singleton objects that don\'t use instance/reference counters be considered memory leaks in C++?

Without a counter that calls for explicit deletion of the singlet

12条回答
  •  被撕碎了的回忆
    2021-01-31 04:45

    I ran into an issue like this and I think this should work even if the main thread exits first and takes the static objects with it. Instead of this:

    Singleton &get_singleton() {
       static Singleton singleton;
       return singleton;
    }
    

    I'm thinking

    Singleton &get_singleton() {
       static std::shared_ptr singleton = std::make_shared();
       static thread_local std::shared_ptr local = singleton;
       return *local;
    }
    

    so when the main thread exits and takes singleton with it, each thread still has its own local shared_ptr that keeps the one Singleton alive.

提交回复
热议问题