I have implemented two methods of how I think a Singleton class should be implemented, I just want the opinion of programmers to which one is the best method to use.
Each of the methods uses these classes:
class Animal {
public:
virtual void speak() const = 0;
};
class Dog {
virtual void speak() { cout << "Woof!!"; }
};
First method:
class AnimalFactory {
public:
static Animal* CreateInstance(int theTypeOfAnimal);
private:
AnimalFactory() { };
static int count; // this will be used to count the number of objects created
static int maxCount; // this is the max count allowed.
};
int AnimalFactory::count = 0;
int AnimalFactory::maxCount = 1;
Animal* AnimalFactory::CreateInstance(int theTypeOfAnimal)
{
Animal* pAnimal = NULL;
if(pAnimal != NULL)
{
return pAnimal;
}
switch(theTypeOfAnimal)
{
case 0:
pAnimal = new Dog();
count++;
break;
case 1:
pAnimal = new Cat();
count++;
break;
case 2:
pAnimal = new Spider();
count++;
break;
default:
cout << "Not known option";
}
return pAnimal;
}
Second Method:
template<typename classType>
class Singleton {
public:
classType& instance()
{
static classType object;
return object;
}
};
Any opinion would be grateful, thanks :)!
In the majority of the cases, Singleton is abused. The general advice is: Don't use it! If you think you really have a case where a Singleton is the correct solution: Probability is still against you. If you are really, really sure you need to use a Singleton, you probably still want to use it as some sort of glorified data: don't. It is gonna hurt you.
OK, you have been warned.
The second approach has the distinct advantage with C++ 2011 that it i thread safe. It also happens to be simpler.
If you are stuck with a compiler not, yet, implementing the C++ 2011 logic and you use your Singleton in a multi-threaded application, you'll need to make sure that it only gets initialized once even if the access function is called concurrently from two threads. Of course, this leads to something else which doesn't work: Do not use the double-checked locking pattern. It [also] doesn't work. If you implemented so that it works, someone will come along and "fix" your code.
Anyway, in embedded environment, you don't need singleton pattern, you don't even need new or malloc.
It's hard to explain, but I try.
Embedded systems must work. There is no IT department armed with manuals and FAQs and internet forums, nobody will tune your Linux system, nobody will fix your config, nobody will install a larger hard disk or memory according to task's needs. Your program can't write a detailed message to stderr and exit() with meaningful error code, if it can, it just means that your embedded system does not work. If you can flash a red led on error, it's better than nothing, but it's still means: device failed.
I think, it's a good practice not to use malloc/free and new/delete. You should "pre-allocate" possible maximum number of objects by defining them as static arrays. Or, if the maximum number of items depends on a configuration which the user can change, you should allocate the fixed number of objects just as program starts, so low memory issue turns out on startup, not half an hour later.
Yes, lot of memory will be wasted, but there will be no mysterious errors. And you have not to deal with memory issues in your program (only at startup).
The first code snippet fails to implement a singleton because AnimalFactory::CreateInstance fails to check the instance count that it maintains.
The second code snippet,
template<typename classType>
class Singleton {
public:
classType& instance()
{
static classType object;
return object;
}
};
when done properly, is called a Meyers' singleton, after Scott Meyers.
The code as given would work but yields awkward usage. To avoid having to instantiate Singleton, the instance method should be declared static. Also, the requirement on classType classes that they should only instantiable by Singleton, should be documented, e.g. as a comment with an example.
Others have already warned you against using singletons, but let me also do that.
Singletons have their uses, such as ensuring that e.g. a Windows API "window class" is only created once, but mainly they're abused as global-variables-in-disguise. One problem with global variables, namely that you don't know when a global variable has been initialized (in C++ programming known as the static initialization order fiasco), is avoided by singletons. However, the main problem, that they serve as spaghetti communication systems, routing chaos-inducing information in untraceable ways between places you would never suspect, is still there.
So, don't.
But if you at some time find that you absolutely need singletons, e.g. for a logging facility, then please do read up on the discussion of singletons in Andrei Alexandrescu's "Modern C++ Design", and then get hold of the Loki library and let it do the job for you.
It looks like you could spare yourself a whole heap of headache by just making a function:
Animal * CreateAnimal(int theTypeOfAnimal)
{
static int count = 0;
static int maxCount = 1;
switch(theTypeOfAnimal)
{
// ...
}
}
Well, the first one doesn't work:
Animal* pAnimal = NULL;
if(pAnimal != NULL)
{
return pAnimal;
}
Do you expect the condition to ever hold?
I've seen the second one before, so I'll go ahead and say it's more idiomatic, at least for this type of singleton, which isn't really a singleton per-say because you have multiple instances, albeit one-per-actual-type. Well, the general idea is okay (for a singleton), but I'd go with something like:
template<typename classType>
class AnimalManager {
public:
static Animal& instance()
{
static classType object;
return object;
}
};
which you could call
Animal& animal = AnimalManager<Dog>::instance();
//assuming you derive Dog from Animal, which you're currently not
I will be downwoted by masses of the Java programmers, but I don't mind: If you know, that your program needs exactly one object instance, feel free to create a global object and write a static get() method which returns (the reference to) it (and don't reference to the global object from elsewhere).
I think, singleton pattern in Java is a technique to implement the global object, in C++ is a technique to hide the global object. But why, it's just as ugly when hidden, as ugly as it's not hidden.
You should also wrap it carefully, in order to make it appear on the scene as other normal objects, and handle it as normal objects. Maybe, later, as the program evolves, there will be more instances of them, and you'll be happy that it already acts as a normal object.
The first solution has some odd coding (see Luchian Grigore answer). Ignoring that:
It is some mix of concepts between a factory and a singleton.
A factory normally is a singleton but what it emits normally is not.
The second one does ensure that you can only create one object of a class, but only iff you wrap it in the Singleton template. If the class has a public constructor, you can create it outside the scheme and thus break the rules.
In my book neither of these is a good way to do a singleton.
To expand a bit: The idea of the singleton is to because you need to manage some specific thing and you need one component to be wholly responsible.
With your first version you can have multiple factories that each create one animal. Doesn't make sense in the real world, doesn't make sense in code.
Your second example tries to allow every call to (optionally) be a singleton - but not all classes need to be, and many will not necessarily behave when "singletonized".
In review, John Vlisides said if one 'pattern' shouldn't have made it into his GOF book it was the singleton. However, also see his discussion of implementing it in C++.
See also Andrei Alexandrescu who explores singletons with 3 different creation models, 4 different lifetime models and 2 threading models, that's 24 ways of implementing a singleton.
Personally, I go out of my way to avoid them by only passing around objects that are needed. It makes testing easier, makes interfaces explicit, etc. You've been warned, of course you've been warned, but will you listen?
Related
Suppose I have a c++ program which with several classes which are related like this:
class Application
{
public:
// some functions
private:
BusinessLogic businessLogic;
// some variables
};
class BusinessLogic
{
public:
// some functions
private:
BusinessLogicSubClass1 businessLogicSubClass1;
BusinessLogicSubClass2 businessLogicSubClass2;
// some other member variables
};
BusinessLogicSubClass1
{
public:
// some functions
private:
SubClassOfSubClass1 subClassOfSubClass1;
// some other member variables
};
// etc.... (you get the idea I hope)
The point is, I know at compile time that there is an Application class that contains the BusinessLogic class which contains many sub classes. I also know that I only need one instance of the Application class. Now the question is how to decide on where to store such a class in memory?
As far as I know there are three main possibilities:
on the stack:
int main()
{
Application application;
// do something with application
return 0;
}
on the heap:
int main()
{
std::unique_ptr application = std::make_unique<Application>();
// do something with application
return 0;
}
as a static:
int main()
{
static Application application;
// do something with application
return 0;
}
I read some information on the different types of memory. Based on what I read, I think it is not the best decision to store the application class on the stack. Mainly because the stack has a limited size and there is a very limited advantage of having the stack's automatic memory management (i.e. cleaning up variables that go out of scope) in this case.
I find it harder to decide however how to make the trade of between static and heap memory. In the simplified example above I think I go with static, because everything is known at compile time and static memory is said to be more efficient, compared to heap memory. (Does this way of thinking make any sense, or am I overlooking something here?)
However, there are some examples in which the choice becomes less evident. Suppose the application needs to be initialized via an .ini file. If you store the instance of the Application class on the heap, it will be possible to pass the initialization values via the constructor:
int main
{
IniFileReader reader;
InitializationValues iniValues = reader.GetIniValues();
std::unique_ptr application = std::make_unique<Application2>(iniValues);
// do something with application
return 0;
}
As far as I know, constructor initialization is considered to be better in terms of design than using some Init function like this:
int main
{
static Application3 application;
IniFileReader reader;
InitializationValues iniValues = reader.GetIniValues();
application.Init(iniValues);
// do something with application
return 0;
}
So here the choice is between cleaner code or a more efficient program. I realize this is sort of trade off is very much dependent on what type of application you intend to build.
What I am looking for is, if there are perhaps some rules of thumb or a sort of flow chart to decide where to store your classes?
Some (not necessarily good) examples of such rules could be:
if you know everything about a class at compile time and you know there is only one instance, try to always store it as a static.
always use the heap for objects that are shared between different threads.
it does not really matter in this or that case, so chose for cleaner code.
And secondly, are there any general guidelines or design principles on where to put the static classes? I find it hard to decide where to put a static class if they need to be accessed by more than one other class. Globals are generally considered bad design for instance.
A practical example of such a dilemma, can be found in the following article on the state design pattern: https://gameprogrammingpatterns.com/state.html --> see subsection static states
I am not sure if the authors choice to put a static instance of each state in the base class is the best design. He also admits to put them there "for no particular reason". Any suggestions for a better place? Make a sort of state-database class? Make a singleton of each state?
edit: changed mistake in code pointed out by Neil Butterworth
One very common way to handle your situation is to use a Singleton design pattern. you can find lots of good references on stack overflow, or via a simple google search. Take a look at this one for example. For you it would look something like this:
class Application
{
public:
static Application& getInstance()
{
static Application instance;
return instance;
}
private:
Application() {}
...
};
For dynamic parameters, I'm not sure I would agree that it's always better to initialize in the constructor, but the details really matter for this. There are cases where it does make sense, and cases where it doesn't. In the singleton case you almost always need some sort of separate "Init" call since you don't want to pass construction arguments on every call to getInstance().
To your question about "heap" versus "static". Assuming you really are only creating one Application instance, and you're running on a "desktop" OS like Linux/Window/MacOS, there will be no meaningful difference in runtime performance between these two. Uninitialized static variables are usually placed in .bss, and the first thing the OS will do when launching your process is dynamically allocate a bunch of pages to make space for the various data sections in your program. Not a whole lot different from what you're doing in code (i.e. a one-time dynamic memory allocation).
Edit:
From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:
So I have read the thread Singletons: good design or a crutch?
And the argument still rages.
I see Singletons as a Design Pattern (good and bad).
The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!).
So the main questions that need to be answered are:
When should you use a Singleton
How do you implement a Singleton correctly
My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses.
So get the ball rolling:
I will hold my hand up and say this is what I use but probably has problems.
I like "Scott Myers" handling of the subject in his books "Effective C++"
Good Situations to use Singletons (not many):
Logging frameworks
Thread recycling pools
/*
* C++ Singleton
* Limitation: Single Threaded Design
* See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
* For problems associated with locking in multi threaded applications
*
* Limitation:
* If you use this Singleton (A) within a destructor of another Singleton (B)
* This Singleton (A) must be fully constructed before the constructor of (B)
* is called.
*/
class MySingleton
{
private:
// Private Constructor
MySingleton();
// Stop the compiler generating methods of copy the object
MySingleton(MySingleton const& copy); // Not Implemented
MySingleton& operator=(MySingleton const& copy); // Not Implemented
public:
static MySingleton& getInstance()
{
// The only instance
// Guaranteed to be lazy initialized
// Guaranteed that it will be destroyed correctly
static MySingleton instance;
return instance;
}
};
OK. Lets get some criticism and other implementations together.
:-)
Answer:
Use a Singleton if:
You need to have one and only one object of a type in system
Do not use a Singleton if:
You want to save memory
You want to try something new
You want to show off how much you know
Because everyone else is doing it (See cargo cult programmer in wikipedia)
In user interface widgets
It is supposed to be a cache
In strings
In Sessions
I can go all day long
How to create the best singleton:
The smaller, the better. I am a minimalist
Make sure it is thread safe
Make sure it is never null
Make sure it is created only once
Lazy or system initialization? Up to your requirements
Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)
Provide a destructor or somehow figure out how to dispose resources
Use little memory
Singletons give you the ability to combine two bad traits in one class. That's wrong in pretty much every way.
A singleton gives you:
Global access to an object, and
A guarantee that no more than one object of this type can ever be created
Number one is straightforward. Globals are generally bad. We should never make objects globally accessible unless we really need it.
Number two may sound like it makes sense, but let's think about it. When was the last time you **accidentally* created a new object instead of referencing an existing one? Since this is tagged C++, let's use an example from that language. Do you often accidentally write
std::ostream os;
os << "hello world\n";
When you intended to write
std::cout << "hello world\n";
Of course not. We don't need protection against this error, because that kind of error just doesn't happen. If it does, the correct response is to go home and sleep for 12-20 hours and hope you feel better.
If only one object is needed, simply create one instance. If one object should be globally accessible, make it a global. But that doesn't mean it should be impossible to create other instances of it.
The "only one instance is possible" constraint doesn't really protect us against likely bugs. But it does make our code very hard to refactor and maintain. Because quite often we find out later that we did need more than one instance. We do have more than one database, we do have more than one configuration object, we do want several loggers. Our unit tests may want to be able to create and recreate these objects every test, to take a common example.
So a singleton should be used if and only if, we need both the traits it offers: If we need global access (which is rare, because globals are generally discouraged) and we need to prevent anyone from ever creating more than one instance of a class (which sounds to me like a design issue). The only reason I can see for this is if creating two instances would corrupt our application state - probably because the class contains a number of static members or similar silliness. In which case the obvious answer is to fix that class. It shouldn't depend on being the only instance.
If you need global access to an object, make it a global, like std::cout. But don't constrain the number of instances that can be created.
If you absolutely, positively need to constrain the number of instances of a class to just one, and there is no way that creating a second instance can ever be handled safely, then enforce that. But don't make it globally accessible as well.
If you do need both traits, then 1) make it a singleton, and 2) let me know what you need that for, because I'm having a hard time imagining such a case.
The problem with singletons is not their implementation. It is that they conflate two different concepts, neither of which is obviously desirable.
1) Singletons provide a global access mechanism to an object. Although they might be marginally more threadsafe or marginally more reliable in languages without a well-defined initialization order, this usage is still the moral equivalent of a global variable. It's a global variable dressed up in some awkward syntax (foo::get_instance() instead of g_foo, say), but it serves the exact same purpose (a single object accessible across the entire program) and has the exact same drawbacks.
2) Singletons prevent multiple instantiations of a class. It's rare, IME, that this kind of feature should be baked into a class. It's normally a much more contextual thing; a lot of the things that are regarded as one-and-only-one are really just happens-to-be-only-one. IMO a more appropriate solution is to just create only one instance--until you realize that you need more than one instance.
One thing with patterns: don't generalize. They have all cases when they're useful, and when they fail.
Singleton can be nasty when you have to test the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.
Other problem is that the Singleton in fact is nothing more than a global variable in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.
It may make dependency tracking harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some Dependency Injection framework to try to alleviate this issue.
Singletons basically let you have complex global state in languages which otherwise make it difficult or impossible to have complex global variables.
Java in particular uses singletons as a replacement for global variables, since everything must be contained within a class. The closest it comes to global variables are public static variables, which may be used as if they were global with import static
C++ does have global variables, but the order in which constructors of global class variables are invoked is undefined. As such, a singleton lets you defer the creation of a global variable until the first time that variable is needed.
Languages such as Python and Ruby use singletons very little because you can use global variables within a module instead.
So when is it good/bad to use a singleton? Pretty much exactly when it would be good/bad to use a global variable.
Modern C++ Design by Alexandrescu has a thread-safe, inheritable generic singleton.
For my 2p-worth, I think it's important to have defined lifetimes for your singletons (when it's absolutely necessary to use them). I normally don't let the static get() function instantiate anything, and leave set-up and destruction to some dedicated section of the main application. This helps highlight dependencies between singletons - but, as stressed above, it's best to just avoid them if possible.
How do you implement a Singleton correctly
There's one issue I've never seen mentioned, something I ran into at a previous job. We had C++ singletons that were shared between DLLs, and the usual mechanics of ensuring a single instance of a class just don't work. The problem is that each DLL gets its own set of static variables, along with the EXE. If your get_instance function is inline or part of a static library, each DLL will wind up with its own copy of the "singleton".
The solution is to make sure the singleton code is only defined in one DLL or EXE, or create a singleton manager with those properties to parcel out instances.
As others have noted, major downsides to singletons include the inability to extend them, and losing the power to instantiate more than one instance, e.g. for testing purposes.
Some useful aspects of singletons:
lazy or upfront instantiation
handy for an object which requires setup and/or state
However, you don't have to use a singleton to get these benefits. You can write a normal object that does the work, and then have people access it via a factory (a separate object). The factory can worry about only instantiating one, and reusing it, etc., if need be. Also, if you program to an interface rather than a concrete class, the factory can use strategies, i.e. you can switch in and out various implementations of the interface.
Finally, a factory lends itself to dependency injection technologies like Spring etc.
The first example isn't thread safe - if two threads call getInstance at the same time, that static is going to be a PITA. Some form of mutex would help.
Singletons are handy when you've got a lot code being run when you initialize and object. For example, when you using iBatis when you setup a persistence object it has to read all the configs, parse the maps, make sure its all correct, etc.. before getting to your code.
If you did this every time, performance would be much degraded. Using it in a singleton, you take that hit once and then all subsequent calls don't have to do it.
The real downfall of Singletons is that they break inheritance. You can't derive a new class to give you extended functionality unless you have access to the code where the Singleton is referenced. So, beyond the fact the the Singleton will make your code tightly coupled (fixable by a Strategy Pattern ... aka Dependency Injection) it will also prevent you from closing off sections of the code from revision (shared libraries).
So even the examples of loggers or thread pools are invalid and should be replaced by Strategies.
Most people use singletons when they are trying to make themselves feel good about using a global variable. There are legitimate uses, but most of the time when people use them, the fact that there can only be one instance is just a trivial fact compared to the fact that it's globally accessible.
Because a singleton only allows one instance to be created it effectively controls instance replication. for example you'd not need multiple instances of a lookup - a morse lookup map for example, thus wrapping it in a singleton class is apt. And just because you have a single instance of the class does not mean you are also limited on the number of references to that instance. You can queue calls(to avoid threading issues) to the instance and effect changes necessary. Yes, the general form of a singleton is a globally public one, you can certainly modify the design to create a more access restricted singleton. I haven't tired this before but I sure know it is possible.
And to all those who commented saying the singleton pattern is utterly evil you should know this: yes it is evil if you do not use it properly or within it confines of effective functionality and predictable behavior: do not GENERALIZE.
But when I need something like a Singleton, I often end up using a Schwarz Counter to instantiate it.
Below is the better approach for implementing a thread safe singleton pattern with deallocating the memory in destructor itself. But I think the destructor should be an optional because singleton instance will be automatically destroyed when the program terminates:
#include<iostream>
#include<mutex>
using namespace std;
std::mutex mtx;
class MySingleton{
private:
static MySingleton * singletonInstance;
MySingleton();
~MySingleton();
public:
static MySingleton* GetInstance();
MySingleton(const MySingleton&) = delete;
const MySingleton& operator=(const MySingleton&) = delete;
MySingleton(MySingleton&& other) noexcept = delete;
MySingleton& operator=(MySingleton&& other) noexcept = delete;
};
MySingleton* MySingleton::singletonInstance = nullptr;
MySingleton::MySingleton(){ };
MySingleton::~MySingleton(){
delete singletonInstance;
};
MySingleton* MySingleton::GetInstance(){
if (singletonInstance == NULL){
std::lock_guard<std::mutex> lock(mtx);
if (singletonInstance == NULL)
singletonInstance = new MySingleton();
}
return singletonInstance;
}
Regarding the situations where we need to use singleton classes can be-
If we want to maintain the state of the instance throughout the execution of the program
If we are involved in writing into execution log of an application where only one instance of the file need to be used....and so on.
It will be appreciable if anybody can suggest optimisation in my above code.
I use Singletons as an interview test.
When I ask a developer to name some design patterns, if all they can name is Singleton, they're not hired.
I find them useful when I have a class that encapsulates a lot of memory. For example in a recent game I've been working on I have an influence map class that contains a collection of very large arrays of contiguous memory. I want that all allocated at startup, all freed at shutdown and I definitely want only one copy of it. I also have to access it from many places. I find the singleton pattern to be very useful in this case.
I'm sure there are other solutions but I find this one very useful and easy to implement.
Anti-Usage:
One major problem with excessive singleton usage is that the pattern prevents easy extension and swapping of alternate implementations. The class-name is hard coded wherever the singleton is used.
I think this is the most robust version for C#:
using System;
using System.Collections;
using System.Threading;
namespace DoFactory.GangOfFour.Singleton.RealWorld
{
// MainApp test application
class MainApp
{
static void Main()
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
// Same instance?
if (b1 == b2 && b2 == b3 && b3 == b4)
{
Console.WriteLine("Same instance\n");
}
// All are the same instance -- use b1 arbitrarily
// Load balance 15 server requests
for (int i = 0; i < 15; i++)
{
Console.WriteLine(b1.Server);
}
// Wait for user
Console.Read();
}
}
// "Singleton"
class LoadBalancer
{
private static LoadBalancer instance;
private ArrayList servers = new ArrayList();
private Random random = new Random();
// Lock synchronization object
private static object syncLock = new object();
// Constructor (protected)
protected LoadBalancer()
{
// List of available servers
servers.Add("ServerI");
servers.Add("ServerII");
servers.Add("ServerIII");
servers.Add("ServerIV");
servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
// Support multithreaded applications through
// 'Double checked locking' pattern which (once
// the instance exists) avoids locking each
// time the method is invoked
if (instance == null)
{
lock (syncLock)
{
if (instance == null)
{
instance = new LoadBalancer();
}
}
}
return instance;
}
// Simple, but effective random load balancer
public string Server
{
get
{
int r = random.Next(servers.Count);
return servers[r].ToString();
}
}
}
}
Here is the .NET-optimised version:
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Singleton.NETOptimized
{
// MainApp test application
class MainApp
{
static void Main()
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
// Confirm these are the same instance
if (b1 == b2 && b2 == b3 && b3 == b4)
{
Console.WriteLine("Same instance\n");
}
// All are the same instance -- use b1 arbitrarily
// Load balance 15 requests for a server
for (int i = 0; i < 15; i++)
{
Console.WriteLine(b1.Server);
}
// Wait for user
Console.Read();
}
}
// Singleton
sealed class LoadBalancer
{
// Static members are lazily initialized.
// .NET guarantees thread safety for static initialization
private static readonly LoadBalancer instance =
new LoadBalancer();
private ArrayList servers = new ArrayList();
private Random random = new Random();
// Note: constructor is private.
private LoadBalancer()
{
// List of available servers
servers.Add("ServerI");
servers.Add("ServerII");
servers.Add("ServerIII");
servers.Add("ServerIV");
servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
return instance;
}
// Simple, but effective load balancer
public string Server
{
get
{
int r = random.Next(servers.Count);
return servers[r].ToString();
}
}
}
}
You can find this pattern at dotfactory.com.
The Meyers singleton pattern works well enough most of the time, and on the occasions it does it doesn't necessarily pay to look for anything better. As long as the constructor will never throw and there are no dependencies between singletons.
A singleton is an implementation for a globally-accessible object (GAO from now on) although not all GAOs are singletons.
Loggers themselves should not be singletons but the means to log should ideally be globally-accessible, to decouple where the log message is being generated from where or how it gets logged.
Lazy-loading / lazy evaluation is a different concept and singleton usually implements that too. It comes with a lot of its own issues, in particular thread-safety and issues if it fails with exceptions such that what seemed like a good idea at the time turns out to be not so great after all. (A bit like COW implementation in strings).
With that in mind, GOAs can be initialised like this:
namespace {
T1 * pt1 = NULL;
T2 * pt2 = NULL;
T3 * pt3 = NULL;
T4 * pt4 = NULL;
}
int main( int argc, char* argv[])
{
T1 t1(args1);
T2 t2(args2);
T3 t3(args3);
T4 t4(args4);
pt1 = &t1;
pt2 = &t2;
pt3 = &t3;
pt4 = &t4;
dostuff();
}
T1& getT1()
{
return *pt1;
}
T2& getT2()
{
return *pt2;
}
T3& getT3()
{
return *pt3;
}
T4& getT4()
{
return *pt4;
}
It does not need to be done as crudely as that, and clearly in a loaded library that contains objects you probably want some other mechanism to manage their lifetime. (Put them in an object that you get when you load the library).
As for when I use singletons? I used them for 2 things
- A singleton table that indicates what libraries have been loaded with dlopen
- A message handler that loggers can subscribe to and that you can send messages to. Required specifically for signal handlers.
I still don't get why a singleton has to be global.
I was going to produce a singleton where I hid a database inside the class as a private constant static variable and make class functions that utilize the database without ever exposing the database to the user.
I don't see why this functionality would be bad.
If you are the one who created the singleton and who uses it, dont make it as singleton (it doesn't have sense because you can control the singularity of the object without making it singleton) but it makes sense when you a developer of a library and you want to supply only one object to your users (in this case you are the who created the singleton, but you aren't the user).
Singletons are objects so use them as objects, many people accesses to singletons directly through calling the method which returns it, but this is harmful because you are making your code knows that object is singleton, I prefer to use singletons as objects, I pass them through the constructor and I use them as ordinary objects, by that way, your code doesn't know if these objects are singletons or not and that makes the dependencies more clear and it helps a little for refactoring ...
In desktop apps (I know, only us dinosaurs write these anymore!) they are essential for getting relatively unchanging global application settings - the user language, path to help files, user preferences etc which would otherwise have to propogate into every class and every dialog.
Edit - of course these should be read-only !
Another implementation
class Singleton
{
public:
static Singleton& Instance()
{
// lazy initialize
if (instance_ == NULL) instance_ = new Singleton();
return *instance_;
}
private:
Singleton() {};
static Singleton *instance_;
};
i was wondering if it is possible to force an object to be created on the heap by creating a private/protected desctuctor and by using shared_ptrs to ensure an automatic resource managment (the RAII features of a shared_ptr) at the same time.
Can that be done in a different way maybe?
The reason i ask that, is because from what i heard(didnt look at that yet) at the STL there are no virtual descructors,so there is no way to ensure safe destruction other than...shared_ptr?
And if so,there is no way to force the object to the heap since shared_ptr is trying to access the destuctor.
Anyway to bypass these limitations?
C++ is a language that puts the correctness of the code in the hand of the programmer. Trying to alter that via some convoluted methods typically leads to code that is hard to use or that doesn't work very well. Forcing the hand of the programmer so that (s)he has to create an object on the heap even if that's not "right" for that particular situation is just bad. Let the programmer shoot him-/herself in the foot if he wants to.
In larger projects, code should be reviewed by peers (preferably at least sometimes by more senior staff) for correctness and that it follows the coding guidelines of the project.
I'm not entirely sure how "virtual destructors" relate to "safe destruction" and "shared pointers" - these are three different concepts that are not very closely related - virtual destructors are needed when a class is used as a base-class to derive a new class. STL objects are not meant to be derived from [as a rule, you use templates OR inheritance, although they CAN be combined, it gets very complicated very quickly when you do], so there is no need to use virtual destructors in STL.
If you have a class that is a baseclass, and the storage is done based on pointers or references to the baseclass, then you MUST have virtual destructors - or don't use inheritance.
"safe destruction", I take it, means "no memory leaks" [rather than "correct destruction", which can of course also be a problem - and cause problems with memory leaks]. For a large number of situations, this means "don't use pointers to the object in the first place". I see a lot of examples here on SO where the programmer is calling new for absolutely no reason. vector<X>* v = new vector<X>; is definitely a "bad smell" (Just like fish or meat, something is wrong with the code if it smells bad). And if you are calling new, then using shared pointer, unique pointer or some other "wrapping" is a good idea. But you shouldn't force that concept - there are occasionally good reasons NOT to do that.
"shared pointer" is a concept to "automatically destroy the object when it is no longer in use", which is a useful technique to avoid memory leaks.
Now that I have told you NOT to do this, here's one way to achieve it:
class X
{
private:
int x;
X() : x(42) {};
public:
static shared_ptr<X> makeX() { return make_shared<X>(); }
};
Since the constructor is private, the "user" of the class can't call "new" or create an object of this kind. [You probably also want to put the copy constructor and assignment operator in private or use delete to prevent them from being used].
However, I still think this is a bad idea in the first place.
The answer by Mats is indeed wrong. The make_shared needs a public constructor.
However, the following is valid:
class X
{
private:
int x;
X() : x( 42 ) {};
public:
static std::shared_ptr<X> makeX()
{
return std::shared_ptr<X>( new X() );
}
};
I don't like to use the new keyword, but in this case, it is the only way.
I have a class, named Contoller. I want to create one object from that class and change transactionValue and transactionId over and over in runtime. What is the best way for that. I think I can create one object from default constructer and use setControllerValues for new values. Is it best practice?
class Controller{
public:
Controller();
Controller(int,int);
setControllerValues(int,int);
private:
int transactionValue;
int transactionId;
};
int main()
{
Controller ct;
ct.setControllerValues(3,4);
ct.setControllerValues(6,7);
ct.setControllerValues(34,45);
}
EDIT:I heard something about singleton. Should I use it for that?(I changed "skeleton")
Make it a global! No, wait, globals are bad. Make it a singleton! No, wait, singletons are an anti-pattern. Pass it as an argument wherever it's needed! No, wait, tramp data is bad. Make it a global!
What's a person to do?
You pays your money and you takes your choice.
Yes it can be considered good practice. There's nothing wrong there. Maybe you want to do some data validation before writing to your private members in setControllerValues. But a part from that that's pretty straight forward OOP you have there.
It depends.
Some programs are far easier to reason about if there is no mutable state (or very little); multi-threaded programs, for example.
Other object oriented approaches would say getters and setters are anathema.
In terms of performance and creating new objects on the stack, c++11 and the compiler are very good at working out the best way of creating efficient machine code, far better than you and me.
I would consider using the assignment operator. It allows you to use the values from one object to modify another:
class Controller {
public:
Controller& operator=(const Controller& other) {
transactionValue = other.transactionValue;
transactionId = other.transactionId;
return *this;
}
private:
int transactionValue;
int transactionId;
};
And use:
Controller permanent(12, 5678);
//...
permanent = Controller(23, 6789);
What you heard is probably singleton, not skeleton.
For sure, you can use the approach you show, but let me ask you: why would you choose this instead of creating separate objects?
I don't like it for following reasons:
if you really want to ensure a single instance over whole application, you need a proper singleton (not that I like it). Your current implementation doesn't stop anyone to create another controller
it is much easier to handle multiple instances then shared access to single instance. What if you have to provide this object to other functions, or even worse, threads?
it is easier to reason about immutable objects than mutable ones. Mutable state is the cause of good deal of bugs, as it gives more chance to invalidate the type invariants
you actually gain nothing but the cost of calling a constructor which is cheap compared to other logic you need to execute
In short, I don't see any benefit in this approach, without knowing other requirements which might make it more justified. You have introduced a lot of added complexity to save a few instructions during object creation, which is optimized by the compiler anyway. It is a bad tradeoff, IMO.
With regard to singletons, in general I don't like them either :)
Here's why:
I am very suspicious about the class itself knowing its lifecycle concerns (singleton, transient, per-thread, etc). This is something that clients usually know better
It is much harder to test code relying on singletons
shared state + multithreading = nights with debugger
That being said, sometimes they make perfect sense. However, you example doesn't seem to be such a case.
Edit:
From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:
So I have read the thread Singletons: good design or a crutch?
And the argument still rages.
I see Singletons as a Design Pattern (good and bad).
The problem with Singleton is not the Pattern but rather the users (sorry everybody). Everybody and their father thinks they can implement one correctly (and from the many interviews I have done, most people can't). Also because everybody thinks they can implement a correct Singleton they abuse the Pattern and use it in situations that are not appropriate (replacing global variables with Singletons!).
So the main questions that need to be answered are:
When should you use a Singleton
How do you implement a Singleton correctly
My hope for this article is that we can collect together in a single place (rather than having to google and search multiple sites) an authoritative source of when (and then how) to use a Singleton correctly. Also appropriate would be a list of Anti-Usages and common bad implementations explaining why they fail to work and for good implementations their weaknesses.
So get the ball rolling:
I will hold my hand up and say this is what I use but probably has problems.
I like "Scott Myers" handling of the subject in his books "Effective C++"
Good Situations to use Singletons (not many):
Logging frameworks
Thread recycling pools
/*
* C++ Singleton
* Limitation: Single Threaded Design
* See: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
* For problems associated with locking in multi threaded applications
*
* Limitation:
* If you use this Singleton (A) within a destructor of another Singleton (B)
* This Singleton (A) must be fully constructed before the constructor of (B)
* is called.
*/
class MySingleton
{
private:
// Private Constructor
MySingleton();
// Stop the compiler generating methods of copy the object
MySingleton(MySingleton const& copy); // Not Implemented
MySingleton& operator=(MySingleton const& copy); // Not Implemented
public:
static MySingleton& getInstance()
{
// The only instance
// Guaranteed to be lazy initialized
// Guaranteed that it will be destroyed correctly
static MySingleton instance;
return instance;
}
};
OK. Lets get some criticism and other implementations together.
:-)
Answer:
Use a Singleton if:
You need to have one and only one object of a type in system
Do not use a Singleton if:
You want to save memory
You want to try something new
You want to show off how much you know
Because everyone else is doing it (See cargo cult programmer in wikipedia)
In user interface widgets
It is supposed to be a cache
In strings
In Sessions
I can go all day long
How to create the best singleton:
The smaller, the better. I am a minimalist
Make sure it is thread safe
Make sure it is never null
Make sure it is created only once
Lazy or system initialization? Up to your requirements
Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)
Provide a destructor or somehow figure out how to dispose resources
Use little memory
Singletons give you the ability to combine two bad traits in one class. That's wrong in pretty much every way.
A singleton gives you:
Global access to an object, and
A guarantee that no more than one object of this type can ever be created
Number one is straightforward. Globals are generally bad. We should never make objects globally accessible unless we really need it.
Number two may sound like it makes sense, but let's think about it. When was the last time you **accidentally* created a new object instead of referencing an existing one? Since this is tagged C++, let's use an example from that language. Do you often accidentally write
std::ostream os;
os << "hello world\n";
When you intended to write
std::cout << "hello world\n";
Of course not. We don't need protection against this error, because that kind of error just doesn't happen. If it does, the correct response is to go home and sleep for 12-20 hours and hope you feel better.
If only one object is needed, simply create one instance. If one object should be globally accessible, make it a global. But that doesn't mean it should be impossible to create other instances of it.
The "only one instance is possible" constraint doesn't really protect us against likely bugs. But it does make our code very hard to refactor and maintain. Because quite often we find out later that we did need more than one instance. We do have more than one database, we do have more than one configuration object, we do want several loggers. Our unit tests may want to be able to create and recreate these objects every test, to take a common example.
So a singleton should be used if and only if, we need both the traits it offers: If we need global access (which is rare, because globals are generally discouraged) and we need to prevent anyone from ever creating more than one instance of a class (which sounds to me like a design issue). The only reason I can see for this is if creating two instances would corrupt our application state - probably because the class contains a number of static members or similar silliness. In which case the obvious answer is to fix that class. It shouldn't depend on being the only instance.
If you need global access to an object, make it a global, like std::cout. But don't constrain the number of instances that can be created.
If you absolutely, positively need to constrain the number of instances of a class to just one, and there is no way that creating a second instance can ever be handled safely, then enforce that. But don't make it globally accessible as well.
If you do need both traits, then 1) make it a singleton, and 2) let me know what you need that for, because I'm having a hard time imagining such a case.
The problem with singletons is not their implementation. It is that they conflate two different concepts, neither of which is obviously desirable.
1) Singletons provide a global access mechanism to an object. Although they might be marginally more threadsafe or marginally more reliable in languages without a well-defined initialization order, this usage is still the moral equivalent of a global variable. It's a global variable dressed up in some awkward syntax (foo::get_instance() instead of g_foo, say), but it serves the exact same purpose (a single object accessible across the entire program) and has the exact same drawbacks.
2) Singletons prevent multiple instantiations of a class. It's rare, IME, that this kind of feature should be baked into a class. It's normally a much more contextual thing; a lot of the things that are regarded as one-and-only-one are really just happens-to-be-only-one. IMO a more appropriate solution is to just create only one instance--until you realize that you need more than one instance.
One thing with patterns: don't generalize. They have all cases when they're useful, and when they fail.
Singleton can be nasty when you have to test the code. You're generally stuck with one instance of the class, and can choose between opening up a door in constructor or some method to reset the state and so on.
Other problem is that the Singleton in fact is nothing more than a global variable in disguise. When you have too much global shared state over your program, things tend to go back, we all know it.
It may make dependency tracking harder. When everything depends on your Singleton, it's harder to change it, split to two, etc. You're generally stuck with it. This also hampers flexibility. Investigate some Dependency Injection framework to try to alleviate this issue.
Singletons basically let you have complex global state in languages which otherwise make it difficult or impossible to have complex global variables.
Java in particular uses singletons as a replacement for global variables, since everything must be contained within a class. The closest it comes to global variables are public static variables, which may be used as if they were global with import static
C++ does have global variables, but the order in which constructors of global class variables are invoked is undefined. As such, a singleton lets you defer the creation of a global variable until the first time that variable is needed.
Languages such as Python and Ruby use singletons very little because you can use global variables within a module instead.
So when is it good/bad to use a singleton? Pretty much exactly when it would be good/bad to use a global variable.
Modern C++ Design by Alexandrescu has a thread-safe, inheritable generic singleton.
For my 2p-worth, I think it's important to have defined lifetimes for your singletons (when it's absolutely necessary to use them). I normally don't let the static get() function instantiate anything, and leave set-up and destruction to some dedicated section of the main application. This helps highlight dependencies between singletons - but, as stressed above, it's best to just avoid them if possible.
How do you implement a Singleton correctly
There's one issue I've never seen mentioned, something I ran into at a previous job. We had C++ singletons that were shared between DLLs, and the usual mechanics of ensuring a single instance of a class just don't work. The problem is that each DLL gets its own set of static variables, along with the EXE. If your get_instance function is inline or part of a static library, each DLL will wind up with its own copy of the "singleton".
The solution is to make sure the singleton code is only defined in one DLL or EXE, or create a singleton manager with those properties to parcel out instances.
As others have noted, major downsides to singletons include the inability to extend them, and losing the power to instantiate more than one instance, e.g. for testing purposes.
Some useful aspects of singletons:
lazy or upfront instantiation
handy for an object which requires setup and/or state
However, you don't have to use a singleton to get these benefits. You can write a normal object that does the work, and then have people access it via a factory (a separate object). The factory can worry about only instantiating one, and reusing it, etc., if need be. Also, if you program to an interface rather than a concrete class, the factory can use strategies, i.e. you can switch in and out various implementations of the interface.
Finally, a factory lends itself to dependency injection technologies like Spring etc.
The first example isn't thread safe - if two threads call getInstance at the same time, that static is going to be a PITA. Some form of mutex would help.
Singletons are handy when you've got a lot code being run when you initialize and object. For example, when you using iBatis when you setup a persistence object it has to read all the configs, parse the maps, make sure its all correct, etc.. before getting to your code.
If you did this every time, performance would be much degraded. Using it in a singleton, you take that hit once and then all subsequent calls don't have to do it.
The real downfall of Singletons is that they break inheritance. You can't derive a new class to give you extended functionality unless you have access to the code where the Singleton is referenced. So, beyond the fact the the Singleton will make your code tightly coupled (fixable by a Strategy Pattern ... aka Dependency Injection) it will also prevent you from closing off sections of the code from revision (shared libraries).
So even the examples of loggers or thread pools are invalid and should be replaced by Strategies.
Most people use singletons when they are trying to make themselves feel good about using a global variable. There are legitimate uses, but most of the time when people use them, the fact that there can only be one instance is just a trivial fact compared to the fact that it's globally accessible.
Because a singleton only allows one instance to be created it effectively controls instance replication. for example you'd not need multiple instances of a lookup - a morse lookup map for example, thus wrapping it in a singleton class is apt. And just because you have a single instance of the class does not mean you are also limited on the number of references to that instance. You can queue calls(to avoid threading issues) to the instance and effect changes necessary. Yes, the general form of a singleton is a globally public one, you can certainly modify the design to create a more access restricted singleton. I haven't tired this before but I sure know it is possible.
And to all those who commented saying the singleton pattern is utterly evil you should know this: yes it is evil if you do not use it properly or within it confines of effective functionality and predictable behavior: do not GENERALIZE.
But when I need something like a Singleton, I often end up using a Schwarz Counter to instantiate it.
Below is the better approach for implementing a thread safe singleton pattern with deallocating the memory in destructor itself. But I think the destructor should be an optional because singleton instance will be automatically destroyed when the program terminates:
#include<iostream>
#include<mutex>
using namespace std;
std::mutex mtx;
class MySingleton{
private:
static MySingleton * singletonInstance;
MySingleton();
~MySingleton();
public:
static MySingleton* GetInstance();
MySingleton(const MySingleton&) = delete;
const MySingleton& operator=(const MySingleton&) = delete;
MySingleton(MySingleton&& other) noexcept = delete;
MySingleton& operator=(MySingleton&& other) noexcept = delete;
};
MySingleton* MySingleton::singletonInstance = nullptr;
MySingleton::MySingleton(){ };
MySingleton::~MySingleton(){
delete singletonInstance;
};
MySingleton* MySingleton::GetInstance(){
if (singletonInstance == NULL){
std::lock_guard<std::mutex> lock(mtx);
if (singletonInstance == NULL)
singletonInstance = new MySingleton();
}
return singletonInstance;
}
Regarding the situations where we need to use singleton classes can be-
If we want to maintain the state of the instance throughout the execution of the program
If we are involved in writing into execution log of an application where only one instance of the file need to be used....and so on.
It will be appreciable if anybody can suggest optimisation in my above code.
I use Singletons as an interview test.
When I ask a developer to name some design patterns, if all they can name is Singleton, they're not hired.
I find them useful when I have a class that encapsulates a lot of memory. For example in a recent game I've been working on I have an influence map class that contains a collection of very large arrays of contiguous memory. I want that all allocated at startup, all freed at shutdown and I definitely want only one copy of it. I also have to access it from many places. I find the singleton pattern to be very useful in this case.
I'm sure there are other solutions but I find this one very useful and easy to implement.
Anti-Usage:
One major problem with excessive singleton usage is that the pattern prevents easy extension and swapping of alternate implementations. The class-name is hard coded wherever the singleton is used.
I think this is the most robust version for C#:
using System;
using System.Collections;
using System.Threading;
namespace DoFactory.GangOfFour.Singleton.RealWorld
{
// MainApp test application
class MainApp
{
static void Main()
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
// Same instance?
if (b1 == b2 && b2 == b3 && b3 == b4)
{
Console.WriteLine("Same instance\n");
}
// All are the same instance -- use b1 arbitrarily
// Load balance 15 server requests
for (int i = 0; i < 15; i++)
{
Console.WriteLine(b1.Server);
}
// Wait for user
Console.Read();
}
}
// "Singleton"
class LoadBalancer
{
private static LoadBalancer instance;
private ArrayList servers = new ArrayList();
private Random random = new Random();
// Lock synchronization object
private static object syncLock = new object();
// Constructor (protected)
protected LoadBalancer()
{
// List of available servers
servers.Add("ServerI");
servers.Add("ServerII");
servers.Add("ServerIII");
servers.Add("ServerIV");
servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
// Support multithreaded applications through
// 'Double checked locking' pattern which (once
// the instance exists) avoids locking each
// time the method is invoked
if (instance == null)
{
lock (syncLock)
{
if (instance == null)
{
instance = new LoadBalancer();
}
}
}
return instance;
}
// Simple, but effective random load balancer
public string Server
{
get
{
int r = random.Next(servers.Count);
return servers[r].ToString();
}
}
}
}
Here is the .NET-optimised version:
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Singleton.NETOptimized
{
// MainApp test application
class MainApp
{
static void Main()
{
LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
LoadBalancer b4 = LoadBalancer.GetLoadBalancer();
// Confirm these are the same instance
if (b1 == b2 && b2 == b3 && b3 == b4)
{
Console.WriteLine("Same instance\n");
}
// All are the same instance -- use b1 arbitrarily
// Load balance 15 requests for a server
for (int i = 0; i < 15; i++)
{
Console.WriteLine(b1.Server);
}
// Wait for user
Console.Read();
}
}
// Singleton
sealed class LoadBalancer
{
// Static members are lazily initialized.
// .NET guarantees thread safety for static initialization
private static readonly LoadBalancer instance =
new LoadBalancer();
private ArrayList servers = new ArrayList();
private Random random = new Random();
// Note: constructor is private.
private LoadBalancer()
{
// List of available servers
servers.Add("ServerI");
servers.Add("ServerII");
servers.Add("ServerIII");
servers.Add("ServerIV");
servers.Add("ServerV");
}
public static LoadBalancer GetLoadBalancer()
{
return instance;
}
// Simple, but effective load balancer
public string Server
{
get
{
int r = random.Next(servers.Count);
return servers[r].ToString();
}
}
}
}
You can find this pattern at dotfactory.com.
The Meyers singleton pattern works well enough most of the time, and on the occasions it does it doesn't necessarily pay to look for anything better. As long as the constructor will never throw and there are no dependencies between singletons.
A singleton is an implementation for a globally-accessible object (GAO from now on) although not all GAOs are singletons.
Loggers themselves should not be singletons but the means to log should ideally be globally-accessible, to decouple where the log message is being generated from where or how it gets logged.
Lazy-loading / lazy evaluation is a different concept and singleton usually implements that too. It comes with a lot of its own issues, in particular thread-safety and issues if it fails with exceptions such that what seemed like a good idea at the time turns out to be not so great after all. (A bit like COW implementation in strings).
With that in mind, GOAs can be initialised like this:
namespace {
T1 * pt1 = NULL;
T2 * pt2 = NULL;
T3 * pt3 = NULL;
T4 * pt4 = NULL;
}
int main( int argc, char* argv[])
{
T1 t1(args1);
T2 t2(args2);
T3 t3(args3);
T4 t4(args4);
pt1 = &t1;
pt2 = &t2;
pt3 = &t3;
pt4 = &t4;
dostuff();
}
T1& getT1()
{
return *pt1;
}
T2& getT2()
{
return *pt2;
}
T3& getT3()
{
return *pt3;
}
T4& getT4()
{
return *pt4;
}
It does not need to be done as crudely as that, and clearly in a loaded library that contains objects you probably want some other mechanism to manage their lifetime. (Put them in an object that you get when you load the library).
As for when I use singletons? I used them for 2 things
- A singleton table that indicates what libraries have been loaded with dlopen
- A message handler that loggers can subscribe to and that you can send messages to. Required specifically for signal handlers.
I still don't get why a singleton has to be global.
I was going to produce a singleton where I hid a database inside the class as a private constant static variable and make class functions that utilize the database without ever exposing the database to the user.
I don't see why this functionality would be bad.
If you are the one who created the singleton and who uses it, dont make it as singleton (it doesn't have sense because you can control the singularity of the object without making it singleton) but it makes sense when you a developer of a library and you want to supply only one object to your users (in this case you are the who created the singleton, but you aren't the user).
Singletons are objects so use them as objects, many people accesses to singletons directly through calling the method which returns it, but this is harmful because you are making your code knows that object is singleton, I prefer to use singletons as objects, I pass them through the constructor and I use them as ordinary objects, by that way, your code doesn't know if these objects are singletons or not and that makes the dependencies more clear and it helps a little for refactoring ...
In desktop apps (I know, only us dinosaurs write these anymore!) they are essential for getting relatively unchanging global application settings - the user language, path to help files, user preferences etc which would otherwise have to propogate into every class and every dialog.
Edit - of course these should be read-only !
Another implementation
class Singleton
{
public:
static Singleton& Instance()
{
// lazy initialize
if (instance_ == NULL) instance_ = new Singleton();
return *instance_;
}
private:
Singleton() {};
static Singleton *instance_;
};