我需要具有应用程序生命周期的单例,保证创建/销毁和对其的静态访问。
#include <iostream>
#include <cstdlib>
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
#define M() C::sM()
#define M2() C::sM2()
using namespace std;
class C {
private:
static C* s;
~C() { cout << "~C()" << endl; }
static C* instance() {
if (s==NULL) { s=new C(); }
cout << "instance()=" << s << endl; return s;
}
static void cleanUp() { delete s; }
void m() { cout << "m()" << endl; }
void m2() { cout << "m2()" << endl; }
DISALLOW_COPY_AND_ASSIGN(C);
public:
C() {
cout << "C()" << endl; if (s==NULL) {
s=this; atexit(&cleanUp);
cout << "cleanUp is installed" << endl;
} else {
cout << "cleanUp is not installed" << endl;
}
}
void* operator new(size_t sz) {
void* p=NULL; if (s==NULL) { p=new char[sz]; } else { p=s; }
cout << "new(" << sz << ")=" << p << endl;
return p;
}
void operator delete(void* p, size_t sz) {
cout << "delete(" << sz << "," << p << ")" << endl;
if (p) delete[] static_cast<char*>(p); s=NULL;
}
void static sM() { cout << "sM()" << endl; instance()->m(); }
void static sM2() { cout << "sM2()" << endl; instance()->m2(); }
};
C* C::s = NULL;
int main() {
M();
M2();
C* p1 = new C();
C* p2 = new C();
}
但我不知道如何摆脱 g++ 警告:
test.cpp: In static member function 'static void C::operator delete(void*, size_t)':
test.cpp:22: warning: deleting 'void*' is undefined
如果我写 C* 而不是 void*,析构函数开始在无限循环中调用自己。任何人都可以帮助我在没有警告的情况下获得干净的代码吗?当然是 C++98。