联系
Knight's Blog » 工作

Non-Memory Leak version Singleton pattern implementation with C++

2010-06-03 10:53

I wrote a <a href="http://www.liaoqiqi.com/blog/2010/06/01/writting-your-codes-with-singleton-design-pattern-in-c/">single pattern with C++ implementation</a>[1] article the day before yesterday. However, this version has one fatal problem: it has Memory Leak  error! This is because you use "new" to malloc memory explicitly, but you never delete it manually. Although OS will help you free this heap, you program reallly exist memory leak problem.

It's well known that Java has garbage collector, so he never thinks of freeing the memory. But we are C++ programmers, we should free heap memory if we new/malloc them.

Ok, Now I'll introduce my C++ single pattern correct version: <!--more--> <pre class="brush: cpp; ruler:true ">class S { public: static S&amp; getInstance() { static S instance; // Guaranteed to be destroyed. // Instantiated on first use. return instance; } void setA(int aa){this-&gt;a = aa;} int getA(){return a;}

private: int a; S(){a = 22;} // Dont forget to declare these two. You want to make sure they // are unaccessable otherwise you may accidently get copies of // your singelton appearing. S(S const&amp;){}; // Don't Implement void operator=(S const&amp;){}; // Don't implement };

void main() { int val = S::getInstance().getA(); // we get 22 S::getInstance().setA(10); val = S::getInstance().getA(); // we get 10 } </pre> I hope this version can fit your demand.

Thank you. <h3>Reference:</h3> [1].  <a href="http://www.liaoqiqi.com/blog/2010/06/01/writting-your-codes-with-singleton-design-pattern-in-c/">http://www.liaoqiqi.com/blog/2010/06/01/writting-your-codes-with-singleton-design-pattern-in-c/ </a>[2]. <a href="http://stackoverflow.com/questions/1008019/c-singleton-design-pattern">http://stackoverflow.com/questions/1008019/c-singleton-design-pattern</a> [3]. <a href="http://stackoverflow.com/questions/270947/can-any-one-provide-me-a-sample-of-singleton-in-c/271104#271104">http://stackoverflow.com/questions/270947/can-any-one-provide-me-a-sample-of-singleton-in-c/271104#271104</a>