This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C++ singleton vs completely static object
Hi,
why should I prefer a singleton over static class methods.
MoneyPrinter::addJob(PrinterJob &job);
or
MoneyPrinter::getInstance().addJob(PrinterJob &job);
Is it only a matter of style?
What do you use? Why?
ps. I know that sigletons are not threadsafe (first initialization) by default.
why should I prefer a singleton over static class methods
A singleton can have internal state (in your example, the list of added jobs), i.e. the member data of the singleton class.
What do you use? Why?
If there's no state, then a static method because that's simplest.
Otherwise a singleton, preferably static-initialized (instead of just-in-time or run-time initialized).
A singleton gives you control over when the class is instantiated and as DeadMG points out if you want to instantiate it. A static class is less controllable and is instantiated before main is called.
The sequence in which classes is instantiated can sometimes be critical when the singleton depends on some other class or resource which is not avaiable before main is called.
As you mentioned, if you call a singleton from multiple threads you need to ensure that you have used a thread safe singleton. Scott Meyer's (from Effective C++) is not thread safe for example.
Would be harder to refactor out the Singleton-ness simply because of the syntax used if you use static member functions. There's one reason.
The general rule of singletons is, if you have to ask, don't use it. This is true for any globally mutable state.
Related
I've typically gotten used to implementing a singleton pattern in this manner because it's so easy:
class MyClass
{
public:
MyClass* GetInstance()
{
static MyClass instance;
return &instance;
}
private:
//Disallow copy construction, copy assignment, and external
//default construction.
};
This seems significantly easier than creating a static instance pointer, initializing it in the source file, and using dynamic memory allocation in the instance function with guards.
Is there a downside that I'm not seeing? It looks thread-safe to me because I would think the first thread to get to the first line would cause the instantiation - and it seems nice and concise. I figure there has to be a problem I'm not seeing since this is not common though - I'd like to get some feedback before I keep using it
This is not an inherent threadsafe solution: while constructing the instance, another thread can preempt and try to get the instance, resulting in either a double instance or in using an unconstructed instance.
This is handled by several compilers by adding a guard (in gcc, I think there is a flag to disable this) because there is no way to guard this with a userdefined mutex.
The downside is that you have no control over exactly when the object is destroyed. This will be a problem if other static objects try to access it from their destructors.
A C++11 compliant compiler must implement this in a thread-safe way; however, older compilers might not. If you're in doubt, and you don't especially want lazy initialisation, you could force the object to be created by calling the accessor before starting any threads.
There are two issues in the interface:
You should return a reference
You should make either the destructor or the delete operator private
Also, there is a slight risk of attempting to using this class after it's been destructed.
Regarding your multi-threading concerns (and initialization I guess): it's fine in C++11 and have been fine for a long time on good C++ compilers anyway.
Aside from in a multi-threaded scenario - no. Well - let me qualify this, construction is lazy (so the first call may have a hit) and destruction - well, there is no guarantee (aside from it will be - at some point)
Generally speaking, qualifier static for local variable in a method doesn't guarantee that the variable is created only once. If the method is called by different threads, it could be created once for each thread so many times, as many threads called it. It should be not confused with static member of the class, which is created once before program is started. Thread safety of local static variables depends on particular realization of c++. Useful link : Are function static variables thread-safe in GCC?
Hope it helps.
I have heard that using static member objects is not a very good practice.
Say for example, I have this code:
class Foo {
...
static MyString str;
};
I define and initialize this variable in the implementation file of this class as:
MyString Foo::str = "Some String"; // This is fine as my string API handles this.
When I run this code, I get a warning:
warning:'Foo::str' requires global construction.
I have quite much of such members in my class, what is the best way to handle this.
Thanks,
Most of the arguments against them are the same as for global variables:
Initialization order between different compilation units is undefined.
Initialization order inside one compilation unit may affect the behavior — thus non trivial ordering may be required.
If a constructor throws an exception you can't catch it, your program is terminated.
APPENDED: To handle this properly you must either make sure that above points don't apply to your code and ignore the warning, or redesign your program: Do you really need them static? Why not use const char* Foo::str = "Some String";?
The biggest reason for concern with this example is that constructing the static member object happens before main() and destruction happens after main() (or when you call exit()). So far, that's a good thing. But when you have multiple objects like this in your program, you risk a bug where code attempts to use an object that has not yet been constructed or has already been destroyed.
The C++ FAQ Lite has some helpful discussion on this topic, including a workaround/solution. Recommended reading is questions 10.14 through 10.18. 10.17 is most directly applicable to your example.
Using a static member, you are not guaranteeing thread safety, imagine two threads trying to access the static member - now what would be the value of that member - was it the one from thread x or thread y, this also induces another side-effect, race conditions, where one thread modifies the static member before the other thread completes... in other words, using a static member can be hazardous...
As an example, it is required to know the number of instances of a class. This would require a class static member to track the count of instances.
There is nothing wrong in having a static member of a class if the problem solution requires such a design. It's just that the nitty gritties have to be taken care as mentioned in other posts.
So I want to access a singleton class from multiple threads. Conceptually I'd think that calling non-const methods on this singleton instance would be not thread-safe. I've been looking online and no one seems to address this possible issue. Is there an actual problem with this, is the only issue with Singleton's thread-safety, the initialization of the instance variable?
A singleton instance has the same thread safety issues as any other instance, so calls to its methods or access to its members should be synchronized.
The initialization of the singleton itself is another issue...in gcc static initialization is threadsafe, but probably not so much on other platforms.
Also take a look at this paper addressing some threading singleton issues by Andrei Alexandrescu. His Modern C++ Design book also addresses singleton issues.
You are correct, calling a non-const methods or methods that depend on instance data that could be modified by other threads must be syncronized.
Apart from the thread-safety issue with the initialization of instance variable, the singleton objects should be treated as any other normal objects with respect to thread-safety for the method calls.
ie, Any methods ( you need synchronization for const method as well, if we are trying to read the value of a variable, which will get updated in another method by another thread) of the singleton object accessed by multiple threads and involves in shared data read\write must be synchronized.
Both Marshall Clines' "C++ FAQ Lite" and Scott Meyers' Effective C++ suggest using functions returning local static objects to avoid possible problems with non-local static object initialization order.
In short (from "Effective C++", 3rd edition by Scott Meyers):
FileSystem& tfs()
{
static FileSystem fs;
return fs;
}
Both writers add that this is similar to the Singleton pattern, except that this does not ensure that the local fs is the only instance of a FileSystem.
Now, in a situation where one instance of resource-managing class T is enough, what would be your reasons to prefer a Singleton class or this local static approach over one another? It is not strictly necessary to limit using the class T to just one instance, although our application does not need more than one.
Obviously having a global object is an issue when doing TDD, but in this case both approaches are global.
You can use both:
class Singleton {
public:
static Singleton & Instance() {
static Singleton s;
return s;
}
private:
Singleton() {}
};
Now the only way a Singleton can be created is via the Instance function (because the constructor is private) and so you can guarantee only one Singleton exists. If you want to use the free function approach described in your question, you could consider making the function a friend of the Singleton class while retaining the private constructor.
Note that this construct (as with all constructs that involve static variables) is not thread safe. If thread safety is an issue, you need to consider using something like the double-checked locking pattern when accessing the static Singleton variable.
A Singleton is used when you cannot have more than one object say a CEO class -- obviously two or more CEOs are going to wreck your company;) For a Singleton, you cannot create any more than one object by definition
private ctor
static accessor.
However, function scope local objects are a different beast altogether. This idiom does not preclude the possibility of having other such objects around. This is often found in case of Logger classes where you can create your own Logger objects and the library writer also provides you with a DefaultLogger() function for quick and ugly logging which just wraps over a static Logger object.
Note that some implementations of a Singleton object accessor can use the function scope variable idiom.
I'll soon be posting an article on my blog, but I'd like to verify I haven't missed anything first.
Find an example I've missed, and I'll cite you on my post.
The topic is failed Singleton implementations: In what cases can you accidentally get multiple instances of a singleton?
So far, I've come up with:
Race Condition on first call to instance()
Incorporation into multiple DLLs or DLL and executable
Template definition of a singleton - actually separate classes
Any other ways I'm missing - perhaps with inheritance?
If you use a static instance field that you initialize in your cpp file, you can get multiple instances (and even worse behavior) if the initialization of some static/global tries to get an instance of your singleton. This is because the order of static initialization across compilation units is undefined.
Inheritance shouldn't be an issue as long as the ctor is private.
However, if you don't disallow the copy constructor, users may [un]intentionally copy the singleton instance. Privately inheriting from boost::noncopyable is the easiest way to prevent this.