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;}I hope this version can fit your demand.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 }
Thank you.