Memory leaks when using a singleton

℡╲_俬逩灬. 提交于 2019-12-04 11:22:10

One common way of implementing singleton in C++ is making the instance a function-static std::unique_ptr<T> inside the instance getter, rather than a class-static variable. This ensures a call of destructor upon program's completion, and lets you create an instance that gets accessed polymorphically e.g. through a pointer to an abstract base class.

Scott Meyers provided a good discussion of this topic in his "More Effective C++" book.

Make Manager a static object, and it's constructor and destructor will automatically be called. Or if you must allocate it with operator new, put it in a smart pointer (unique_ptr if you can, otherwise auto_ptr) such that it will be destroyed when the pointer is.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!