Hello everyone,
Well, I kinda solved the leak I was having with a singleton for those of you who remember this issue. I did because I had to build another one to maintain my application configuration settings. It was leaking too. But it also had a non-related bug that, when solved, made the leak go away.
Anyways, I'll try and make this as simple as possible...
Here's a simple example of a singleton with a heap based data member...
As it is, this singleton is reported to leak by Microsoft Visual C++ 2005 Express. Go ahead and try it.Code:class MySingleton { public: static MySingleton& GetInstance() { if (instance_ == NULL) instance_ = new MySingleton(); return *instance_; } ~MySingleton() {} private: static MySingleton* instance_; MySingleton() { heap_.push_back("hello"); } std::vector<std::string> heap_; }; /* implementation file */ MySingleton* MySingleton::instance_ = NULL;
- It leaks inside the vector allocator and in the allocation inside GetInstance().
- It leaks only if you do more than one call to GetInstance().
- But it leaks only once no matter how many calls to GetInstance().
The call code can look something like this, for simplicity :
If it is really leaking or this is an erroneous report ,I'm yet to know. But I strongly suspect the latter.Code:int main() { MySingleton& a = MySingleton::GetInstance(); MySingleton& b = MySingleton::GetInstance(); MySingleton& c = MySingleton::GetInstance(); }
However, if I make heap_ a static data member, the leak goes away. All I'm left with is a leak report of 1 byte pointing to instance_ allocation inside GetInstance(). It's the pointer. This one definitely has to be an erroneous report.
Help me figure this out.