E
Ethan
Hi,
I have a class defined as a "Singleton" (Design Pattern). The codes are
attached below.
My questions are:
1. Does it has mem leak? If no, when did the destructor called? If yes, how
can I avoid it? Purify does not show it has mem leak.
// test if singleto class has mem leakage
#include <iostream>
using namespace std;
class Singleton {
public:
static Singleton* Instance();
~Singleton();
void print();
protected:
Singleton();
private:
static Singleton* _instance;
double* test;
};
Singleton* Singleton::_instance = 0;
Singleton::Singleton() {
test = new double[10];
for (int i=0; i<10; i++) test = i;
}
Singleton::~Singleton() {
cout << "Destructor called!" << endl;
if (test) delete [] test; //
*****************************
}
Singleton*
Singleton::Instance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}
void
Singleton:
rint() {
for (int i=0; i<10; i++) cout << test << endl;
}
int main() {
Singleton::Instance()->print();
}
2. If I remove the line marked "//*********" in the destructor, purify still
shows no mem leak!!!! Obviously this is since "test" was not deleted.
Anybody has some answers?
Thanks,
I have a class defined as a "Singleton" (Design Pattern). The codes are
attached below.
My questions are:
1. Does it has mem leak? If no, when did the destructor called? If yes, how
can I avoid it? Purify does not show it has mem leak.
// test if singleto class has mem leakage
#include <iostream>
using namespace std;
class Singleton {
public:
static Singleton* Instance();
~Singleton();
void print();
protected:
Singleton();
private:
static Singleton* _instance;
double* test;
};
Singleton* Singleton::_instance = 0;
Singleton::Singleton() {
test = new double[10];
for (int i=0; i<10; i++) test = i;
}
Singleton::~Singleton() {
cout << "Destructor called!" << endl;
if (test) delete [] test; //
*****************************
}
Singleton*
Singleton::Instance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}
void
Singleton:
for (int i=0; i<10; i++) cout << test << endl;
}
int main() {
Singleton::Instance()->print();
}
2. If I remove the line marked "//*********" in the destructor, purify still
shows no mem leak!!!! Obviously this is since "test" was not deleted.
Anybody has some answers?
Thanks,