C++ Singleton class returning const reference -
i have class singleton defined follows
class mydata { private: mydata (void); // singleton class. // copy , assignment prohibted. mydata (const mydata &); mydata & operator=(const mydata &); static mydata* s_pinstance; public: ~mydata (void); static const mydata & instance(); static void terminate(); void myfunc() { cout << "my function..." ;} };
// in cpp file.
mydata* mydata::s_pinstance(null); mydata::mydata(){} mydata::~mydata() { s_pinstance = null; } const mydata& mydata::instance() { if (s_pinstance == null) { s_pinstance = new mydata(); } return *(s_pinstance); // want avoid pointer user may deallocate it, used const referense } void main() { (mydata::instance()).myfunc(); }
i getting following error
error c2662: 'mydata::myfunc' : cannot convert 'this' pointer 'const mydata' 'mydata&'
how avoid above problem , call function instance function returning const reference?
thanks!
you'd want declare func()
constant member function, compiler knows won't violate const'd return value instance()
function.
you instead make instance()
function return 'regular' reference apposed const
one.
so either turn: void myfunc()
void myfunc() const
or turn: const mydata& mydata::instance()
mydata& mydata::instance()
Comments
Post a Comment