c++ single instance
时间:2010-03-18 来源:@sky
#include <iostream>
using namespace std;
class Temp {
public:
Temp() { cout << "constructor" << endl; }
~Temp() { cout << "destructor" << endl; }
static Temp * getInstance();
static void putInstance();
private:
static Temp *instance;
};
Temp * Temp::getInstance()
{
cout << "getInstance" << endl;
if (!instance)
instance = new Temp();
return instance;
}
void Temp::putInstance()
{
cout << "putInstance" << endl;
if (instance) {
delete instance;
instance = NULL;
}
}
Temp * Temp::instance = NULL;
int main()
{
Temp *p; /* don't invoke constructor */
p = Temp::getInstance();
Temp::putInstance();
return 0;
}
using namespace std;
class Temp {
public:
Temp() { cout << "constructor" << endl; }
~Temp() { cout << "destructor" << endl; }
static Temp * getInstance();
static void putInstance();
private:
static Temp *instance;
};
Temp * Temp::getInstance()
{
cout << "getInstance" << endl;
if (!instance)
instance = new Temp();
return instance;
}
void Temp::putInstance()
{
cout << "putInstance" << endl;
if (instance) {
delete instance;
instance = NULL;
}
}
Temp * Temp::instance = NULL;
int main()
{
Temp *p; /* don't invoke constructor */
p = Temp::getInstance();
Temp::putInstance();
return 0;
}
相关阅读 更多 +