Singleton Destructors

后端 未结 12 1713
一整个雨季
一整个雨季 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:44

    You can rely on it being cleaned up by the operating system.

    That said, if you are in a garbage collected language with finalizers rather than destructors you may want to have a graceful shutdown procedure that can cleanly shutdown your singletons directly so they can free any critical resources in case there are using system resources that won't be correctly cleaned up by merely ending the application. This is because finalizers run on a sort of 'best effort' basis in most languages. On the other hand there a very very few resources that need this sort of reliability. file handles, memory, etc. all go back to the OS cleanly regardless.

    If you are using a singleton that is lazily allocated (i.e. with a triple-check lock idiom) in a language like c++ with real destructors rather than finalizers, then you cannot rely on its destructor being invoked during program shutdown. If you are using a single static instance then the destructor will run after main completes at some point.

    Regardless, when the process ends, all memory returns to the operating system.

提交回复
热议问题