so eine art singleton
-
Reicht es wenn man ein Objekt von boost/noncopyable ableitet, damit es singulär bleibt oder muss man das anders machen?
#include <boost/utility.hpp> //... class X : boost::noncopyable { // };
-
Sollte nicht reichen:
#include <iostream> #include <boost/utility.hpp> using namespace std; class X : boost::noncopyable { private: int a_; public: const int getA() const { return a_; } }; int main() { X obj; cout << obj.getA() << endl; X obj2; cout << obj2.getA() << endl; X obj3; cout << obj3.getA() << endl; }
siehe:
http://www.bombaydigital.com/arenared/2003/12/4/1
http://www.oop-trainer.de/Themen/Singleton.html
http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.aspVielleicht könnte es so gehen, wenn es von boost:noncopyable abgeleitet sein soll:
#include <iostream> #include <boost/utility.hpp> using namespace std; class X : boost::noncopyable { public: static X* Instance() { static X inst; return &inst; } const int getA() const { return a_; } protected: X(){a_=42;}; private: //static X* pinstance; int a_; }; int main() { X& obj = *X::Instance(); cout << &obj << " " << obj.getA() << endl; X& obj2 = *X::Instance(); cout << &obj2 << " " << obj2.getA() << endl; // gleiches Objekt }
-
noopee schrieb:
Reicht es wenn man ein Objekt von boost/noncopyable ableitet, damit es singulär bleibt
Das eine hat mit dem anderen nichts zu tun.
-
Singletons macht man sich ganz schnell mit Hilfe des Singleton-Templates aus der Loki-Library
struct foo_singleton { void moep(); void bar() const; }; typedef singleton<foo_singleton> foo; int main() { foo::instance().moep(); foo::instance().bar(); }