Memory leaks when using a singleton

前端 未结 2 1834
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 09:42

I have a class in which I implement the singelton design pattern. I know some people don\'t think its a good idea, but it helps a lot,

Anyway - I have a memory leak

相关标签:
2条回答
  • 2020-12-18 10:09

    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.

    0 讨论(0)
  • 2020-12-18 10:29

    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.

    0 讨论(0)
提交回复
热议问题