c++ - Singleton Design Pattern - Explicitly stating a Constructor outside the class -
i trying implement singleton pattern assumption of using private constructor, private instance of class , public static method return instance. encountered error following code in visual studio
// singleton invoice #include <iostream> using namespace std; class singleton { public: //public static method return type of class access instance. static singleton* getinstance(); private: //private constructor singleton(); //private static instance of class static singleton* objsingleton; }; singleton* singleton::objsingleton = null; singleton* singleton::getinstance() { if (objsingleton == null) { //lazy instantiation: if instance not needed never created objsingleton = new singleton(); cout << "object created" << endl; } else { cout << "object created" << endl; } return objsingleton; } int main() { singleton::getinstance(); singleton::getinstance(); singleton::getinstance(); return 0; }
the error :
lnk2019 unresolved external symbol "private: __thiscall singleton::singleton(void)" (??0singleton@@aae@xz) referenced in function "public: static class singleton * __cdecl singleton::getinstance(void)" (?getinstance@singleton@@sapav1@xz)
then resolved error rewriting constructor outside class
singleton::singleton() { }
i know cause error , why constructor needs explicitly written outside class.
in class constructor declared, not defined. definition includes function body. doesn't matter whether define inline in class, or outside class (as did), 1 little difference definition in class it's implicitly inline
.
in other news:
singletons improve on global variables avoiding e.g. static initialization order fiasco, have same problems respect invisible lines of communication , side effects. best avoided.
if don't need singleton persist after corresponding global variable destroyed, use simple meyers' singleton.
here's meyers' singleton:
class foo { private: foo() {} public: static auto instance() -> foo& { static foo the_instance; return the_instance; } };
Comments
Post a Comment