I'd start learning C++ and I don't understand this is memory leak or some kind of voodoo magic?!
I have some "singleton" class (just for a demo):
#include <iostream>
using namespace std;
class S {
private: S() {
cout << "S::S" << endl;
}
public: static S* instance() {
static S* i;
if(i == NULL) {
cout << "Create S" << endl;
i = new S;
}
return i;
}
public: virtual ~S() {
cout << "S::~S" << endl;
}
public: void a() {
cout << "S::a" << endl;
}
};
int main() {
// call some method
S::instance()->a();
// delete pointer to instance (no reason, because I'm curious)
delete S::instance();
// call method again
S::instance()->a();
return 0;
}
Output of these is:
Create S
S::S
S::a
S::~S
S::a
So my question is: Why after destructor call I still have working copy of class S in static variable?
Upd: Thanks for answers. I realize my mistakes. Please, forgive me for disturbing.
The second call to instance is now risky:
S::instance()->a();
It will call:
public: static S* instance() {
static S* i;
if(i == NULL) {
cout << "Create S" << endl;
i = new S;
}
return i;
}
But i is not NULL (although to object is deleted, the pointer to it is invalid), so it returns an pointer to some memory where once was S
. And then you have undefined behaviour, the old object maybe there, it may not, or something far worse can happen.
Conclusion to make it work, make sure when you delete the object always set the pointer to NULL. For example check this answer: How to delete Singleton pointer?