联系
Knight's Tale » 技术

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

2010-06-03 10:53

I wrote a single pattern with C++ implementation[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:

class S
{
public:
    static S& getInstance()
    {
        static S    instance; // Guaranteed to be destroyed.
        // Instantiated on first use.
        return instance;
    }
    void setA(int aa){this->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&){}; // Don't Implement void operator=(S const&){}; // Don't implement };

void main() { int val = S::getInstance().getA(); // we get 22 S::getInstance().setA(10); val = S::getInstance().getA(); // we get 10 }

I hope this version can fit your demand.

Thank you.

Reference:

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