C++ singleton with private constructor -


i need singleton application lifetime, guaranteed creation/destruction , static access it.

#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 installed" << endl;          } else {              cout << "cleanup 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(); }   

but don't know how rid of g++ warning:

test.cpp: in static member function 'static void c::operator delete(void*, size_t)': test.cpp:22: warning: deleting 'void*' undefined 

if write c* instead of void*, destructor start calling in infinite loop. can me clean code without warnings? c++98 of course.

the type delete char*:

void operator delete(void* p, size_t sz) {      cout << "delete(" << sz << "," << p << ")" << endl;     if (p) delete (char*) p; } 

there bug in new: what's difference between new char[10] , new char(10)

maybe should be:

p=new char[sz]; 

and

delete[] (char*)p ; 

---- edited:

the delete purists, sacrificing clarity people learning ;p :

delete[] static_cast<char*>(p) ; 

(*actually appreciate note cast)


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -