Singleton: Difference between revisions
→{{header|C++}}: A proper implementation should only (1) ensure that only one instance exists at any given moment; and (2) provide global access to that instance. Concurrency issues should be considered as a separate matter (in the general case).
(→{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details) |
(→{{header|C++}}: A proper implementation should only (1) ensure that only one instance exists at any given moment; and (2) provide global access to that instance. Concurrency issues should be considered as a separate matter (in the general case).) |
||
Line 201:
=={{header|C++}}==
A generic singleton template class (implemented via the "Curiously Recurring Template Pattern"[https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern]). Warning: if using a version of C++ prior to C++11, a [[Mutex#C|mutex]] (or similar) is required to access static variables within a multi-threaded program.
<lang cpp>
#include <stdexcept>
template <typename Self>
class singleton
{
protected:
static Self*
sentry;
public:
static Self&
instance()
{
return *sentry;
}
singleton()
{
if(sentry)
throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!");
sentry = (Self*)this;
}
virtual ~singleton()
{
if(sentry == this)
sentry = 0;
}
};
template <typename Self>
Self*
singleton<Self>::sentry = 0;
/*
Example usage:
*/
#include <iostream>
#include <string>
using namespace
std;
class controller : public singleton<controller>
{
public:
controller(string const& name)
: name(name)
{
trace("begin");
}
~controller()
{
trace("end");
}
void
work()
{
trace("doing stuff");
}
void
trace(string const& message)
{
cout << name << ": " << message << endl;
}
string
name;
};
int
main()
{
controller*
first = new controller("first");
controller::instance().work();
delete first;
/*
No problem, our first controller no longer exists...
*/
controller
second("second");
controller::instance().work();
try
{
/*
Never happens...
*/
controller
goner("goner");
controller::instance().work();
}
catch(exception const& error)
{
cout << error.what() << endl;
}
controller::instance().work();
/*
Never happens (and depending on your system this may or may not print a helpful message!)
*/
controller
goner("goner");
controller::instance().work();
}
</lang>
=={{header|C sharp|C#}}==
|