I write a singleton c++ in the follow way:
class A {
private:
static A* m_pA;
A();
virtual ~A();
public:
static A* GetInstance();
static void FreeInstance();
void WORK1();
void WORK2();
void WORK3();
}
}
A* A::GetInstance() {
if (m_pA == NULL)
m_pA = new A();
return m_pA;
}
A::~A() {
FreeInstance() // Can I write this? are there any potential error?
}
void A::FreeInstance() {
delete m_pA;
m_pA = NULL;
}
Thanks! Evan Teran and sep61.myopenid.com 's answer is right, and really good!
My way is wrong, I wish any one writting such code can avoid my silly mistake.
My singleton A in my project has a vector of smart pointer, and another thread can also edit this vector, so when the application is closing, it always become unstable even I add lots of CMutex. Multithread error + singleton error wasted me 1 day.
//-----------------------------------------------------------
A new singleton, you are welcome to edit if you think there is any problem in the following sample:
class A {
private:
static A* m_pA;
explicit A();
void A(const A& a);
void A(A &a);
const A& operator=(const A& a);
virtual ~A();
public:
static A* GetInstance();
static void FreeInstance();
void WORK1();
void WORK2();
void WORK3();
}
}
A* A::GetInstance() {
if (m_pA == NULL){
static A self;
m_pA = &self;
}
return m_pA;
}
A::~A() {
}
Why does everybody want to return a singleton as a pointer?
Return it as a reference seems much more logical!
You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don't know (or can't guarantee) nobody has a reference (in your case via a pointer) then you have no business freeing the object.
Use the static in a function method.
This guarantees that it is created and destroyed only once. It also gives you lazy initialization for free.
class S
{
public:
static S& getInstance()
{
static S instance;
return instance;
}
private:
S() {}
S(S const&); // Don't Implement.
void operator=(S const&); // Don't implement
};
Note you also need to make the constructor private.
Also make sure that you override the default copy constructor and assignment operator so that you can not make a copy of the singleton (otherwise it would not be a singleton).
Also read:
https://stackoverflow.com/a/1008289/14065
Singleton: How should it be used
C++ Singleton design pattern
To make sure you are using a singleton for the correct reasons.
Though technically not thread safe in the general case see:
What is the lifetime of a static variable in a C++ function?
GCC has an explicit patch to compensate for this:
http://gcc.gnu.org/ml/gcc-patches/2004-09/msg00265.html
You can avoid needing to delete it by using a static object like this:
if(m_pA == 0) {
static A static_instance;
m_pA = &static_instance;
}
A singleton in C++ can be written in this way:
static A* A::GetInstance() {
static A sin;
return &sin;
}
Just don't forget to make the copy constructor and assignment operators private.
I do not think there is any reason to write that line no. Your destructor method is not static and your singleton instance will not be destructed in that fashion. I do not think the destructor is necessary, if you need to cleanup the object use the static method you've alread created, FreeInstance().
Other than that, you create your singletons in roughly the same way that I create mine.
After a period of wild enthusiasm for Meyers-style singletons (using local static objects as in some of the previous answers), I got completely sick of the lifetime management problems in complicated apps.
I tend to find that you end up referencing the 'Instance' method deliberately early in the app's initialisation, to make sure they're created when you want, and then playing all kinds of games with the tear-down because of the unpredictable (or at least very complicated and somewhat hidden) order in which things get destroyed.
YMMV of course, and it depends a bit on the nature of the singleton itself, but a lot of the waffle about clever singletons (and the threading/locking issues which surround the cleverness) is overrated IMO.
if you read "Modern C++ Design" you'll realize that a singleton design could be much complex than return a static variable.
This implementation is fine as long as you can answer these questions:
do you know when the object will be created (if you use a static object instead of new? Do you have a main()?)
does you singleton have any dependencies that may not be ready by the time it is created? If you use a static object instead of new, what libraries have been initialized by this time? What your object does in constructor that might require them?
when will it be deleted?
Using new() is safer because you control where and when the object will be created and deleted. But then you need to delete it explicitly and probably nobody in the system knows when to do so. You may use atexit() for that, if it makes sense.
Using a static object in method means that do do not really know when it will be created or deleted. You could as well use a global static object in a namespace and avoid getInstance() at all - it doesn't add much.
If you do use threads, then you're in big trouble. It is virtually impossible to create usable thread safe singleton in C++ due to:
permanent lock in getInstance is very heavy - a full context switch at every getInstance()
double checked lock fails due to compiler optimizations and cache/weak memory model, is very tricky to implement, and impossible to test. I wouldn't attempt to do it in a real system, unless you intimately know your architecture and want it to be not portable
These can be Googled easily, but here's a good link on weak memory model: http://ridiculousfish.com/blog/archives/2007/02/17/barrier.
One solution would be to use locking but require that users cache the pointer they get from getInctance() and be prepared for getInstance() to be heavy.
Another solution would be to let users handle thread safety themselves.
Yet another solution would be to use a function with simple locking and substitute it with another function without locking and checking once the new() has been called. This works, but full implementation is complicated.
There is a great C++ library, ACE, based on patterns. There's a lot of documentation about different kind of patterns so look at their work:
http://www.cs.wustl.edu/~schmidt/ACE.html
//! #file singleton.h
//!
//! #brief Variadic template to make a singleton out of an ordinary type.
//!
//! This template makes a singleton out of a type without a default
//! constructor.
#ifndef SINGLETON_H
#define SINGLETON_H
#include <stdexcept>
template <typename C, typename ...Args>
class singleton
{
private:
singleton() = default;
static C* m_instance;
public:
singleton(const singleton&) = delete;
singleton& operator=(const singleton&) = delete;
singleton(singleton&&) = delete;
singleton& operator=(singleton&&) = delete;
~singleton()
{
delete m_instance;
m_instance = nullptr;
}
static C& create(Args...args)
{
if (m_instance != nullptr)
{
delete m_instance;
m_instance = nullptr;
}
m_instance = new C(args...);
return *m_instance;
}
static C& instance()
{
if (m_instance == nullptr)
throw std::logic_error(
"singleton<>::create(...) must precede singleton<>::instance()");
return *m_instance;
}
};
template <typename C, typename ...Args>
C* singleton<C, Args...>::m_instance = nullptr;
#endif // SINGLETON_H
Related
If I return a reference to my instance of MySingleton from GetInstance() instead of the pointer in my code below, it will be valid, but is using the pointer in this way also valid?
I assume my pointer will only get initialized once because it is static, but not not sure.
I know the correct way by using raw pointers within a singleton is to check if the pointer is first null before assigning it, but wondering if the below code is also valid. Thanks
class MySingleton
{
public:
static MySingleton* GetInstance()
{
static MySingleton* inst = new MySingleton();
return inst;
}
private:
MySingleton(){};
};
EDIT: I haven't seen this exact implementation for a Singleton implemented in the reported duplicate question
Your implementation is acceptable (as is any other) as long as any one of the following holds:
Your singleton does not acquire any external resources (anything: file handles, network connections, shared memory) for longer than a single exception-safe method invocation.
The last user of your singleton deletes the instance manually.
Otherwise something serious can leak.
You can wrap the instance in something automatic, like std::unique_ptr, but this immediately casts usual singleton lifetime issues.
See std::call_once and std::once_flag for implementing singleton pattern. Your implementation will lead to troubles in a multithreaded environment.
Most of is seem to have missed the simplest possible form of C++ singleton AKA Scott Meyer's Singleton. Ever since C++11 it has become as easy as a pie:
class singleton{
singleton();
singleton(singleton&&)=delete;
singleton(singleton const&)=delete;
void operator(singleton&&)=delete;
void operator(singleton const&)=delete;
//...
public:
static auto& singleton::instance(){
static singleton val{};
return val;
}
};
No need for complex code.
someone told me just to write singleton as a local class, is that true?
I am wondering why using the local class can ensure thread safety.
#include <boost/utility.hpp>
class singleton : private boost::noncopyable {
public:
static singleton& instance() {
static singleton inst;
return inst;
}
private:
singleton() = default;
~singleton() = default;
};
The construction of local static variables is guaranteed to be thread-safe.
Also, avoid singletons at all cost. They are just as terrible as globals are.
Take a look at this post: what is correspoding feature for synchronized in java?feature-for-synchronized-in-java
Basically it states that C++ doesn't has a language level feature for locking mechanisms, wich you need to make your singelton class threadsafe, though this articel http://en.wikipedia.org/wiki/Double-checked_locking about the Double Checked Locking Pattern states, that no locking is needed for singletons (an example is included for c).
I have seen code where the constructor has been declared as private while the destructor is public. What is the use of such a declaration? Is the destructor required to be public so that during inheritance the calls can be possible or is it a bug in the code?
The question might seem to be a bit short on information, but what I really want to know is if having a public destructor when the constructor is required to be private abides by the C++ rules?
Short Answer
Creating a constructor as private but the destructor as public has many practical uses.
You can use this paradigm to:
Enforcing reference counting (See Hitesh Vaghani's example).
Implement the singleton pattern
Implement the factory pattern.
Long Answer
Above I hinted that you can use private constructors and destructors to implement several design patterns. Well, here's how...
Reference Counting
Using private destructor within an object lends itself to a reference counting system. This lets the developer have stronger control of an objects lifetime.
class MyReferenceObject
{
public:
static MyReferenceObject* Create()
{
return new MyReferenceObject();
}
void retain()
{
m_ref_count++;
}
void release()
{
m_ref_count--;
if (m_ref_count <= 0)
{
// Perform any resource/sub object cleanup.
// Delete myself.
delete this; // Dangerous example but demonstrates the principle.
}
}
private:
int m_ref_count;
MyReferenceObject()
{
m_ref_count = 1;
}
~MyReferenceObject() { }
}
int main()
{
new MyReferenceObject(); // Illegal.
MyReferenceObject object; // Illegal, cannot be made on stack as destructor is private.
MyReferenceObject* object = MyReferenceObject::Create(); // Creates a new instance of 'MyReferenceObject' with reference count.
object->retain(); // Reference count of 2.
object->release(); // Reference count of 1.
object->release(); // Reference count of 0, object deletes itself from the heap.
}
This demonstrates how an object can manage itself and prevent developers from corrupting the memory system. Note that this is a dangerous example as MyReferenceObject deletes itself, see here for a list of things to consider when doing this.
Singleton
A major advantage to private constructors and destructors within a singleton class is that enforces the user to use it in only the manner that the code was design. A rogue singleton object can't be created (because it's enforced at compile time) and the user can't delete the singleton instance (again, enforced at compile time).
For example:
class MySingleton
{
public:
MySingleton* Instance()
{
static MySingleton* instance = NULL;
if (!instance)
{
instance = new MySingleton();
}
return instance;
}
private:
MySingleton() { }
~MySingleton() { }
}
int main()
{
new MySingleton(); // Illegal
delete MySingleton::Instance(); // Illegal.
}
See how it is almost impossible for the code to be misused. The proper use of the MySingleton is enforce at compile time, thus ensuring that developers must use MySingleton as intended.
Factory
Using private constructors within the factory design pattern is an important mechanism to enforce the use of only the factory to create objects.
For example:
class MyFactoryObject
{
public:
protected:
friend class MyFactory; // Allows the object factory to create instances of MyFactoryObject
MyFactoryObject() {} // Can only be created by itself or a friend class (MyFactory).
}
class MyFactory
{
public:
static MyFactoryObject* MakeObject()
{
// You can perform any MyFactoryObject specific initialisation here and it will carry through to wherever the factory method is invoked.
return new MyFactoryObject();
}
}
int main()
{
new MyFactoryObject(); // Illegal.
MyFactory::MakeObject(); // Legal, enforces the developer to make MyFactoryObject only through MyFactory.
}
This is powerful as it hides the creation of MyFactoryObject from the developer. You can use the factory method to perform any initilisation for MyFactoryObject (eg: setting a GUID, registering into a DB) and anywhere the factory method is used, that initilisation code will also take place.
Summary
This is just a few examples of how you can use private constructors and destructors to enforce the correct use of your API. If you want to get tricky, you can combine all these design patterns as well ;)
First thing: the destructor can be private.
having a public destructor when the constructor is required to be
private abides by the C++ rules?
It's totally working in C++. In fact, a great example of this scenario is the singleton pattern, where the constructor is private and the destructor is public.
In reverse order.
Is the destructor required to be public so that during inheritance the calls can be possible or is it a bug in the code?
Actually, for inheritance to work the destructor should be at least protected. If you inherit from a class with a private destructor, then no destructor can be generated for the derived class, which actually prevents instantiation (you can still use static methods and attributes).
What is the use of such declaration?
Note that even though the constructor is private, without further indication the class has a (default generated) public copy constructor and copy assignment operator. This pattern occurs frequently with:
the named constructor idiom
a factory
Example of named constructor idiom:
class Angle {
public:
static Angle FromDegrees(double d);
static Angle FromRadian(double d);
private:
Angle(double x): _value(x) {}
double _value;
};
Because it is ambiguous whether x should be precised in degrees or radians (or whatever), the constructor is made private and named method are provided. This way, usage makes units obvious:
Angle a = Angle::FromDegrees(360);
You make constructor private if you want to prevent creating more then one instance of your class. That way you control the creation of intances not their destruction. Thus, the destructor may be public.
One example in my head, let's say you want to limit the class instance number to be 0 or 1.
For example, for some singleton class, you want the application can temprary destroy the object to rducue memory usage. to implement this constructor will be private, but destructor will be public. see following code snippet.
class SingletoneBigMemoryConsumer
{
private:
SingletoneBigMemoryConsumer()
{
// Allocate a lot of resource here.
}
public:
static SingletoneBigMemoryConsumer* getInstance()
{
if (instance != NULL)
return instance;
else
return new SingletoneBigMemoryConsumer();
}
~SingletoneBigMemoryConsumer()
{
// release the allocated resource.
instance = NULL;
}
private:
// data memeber.
static SingletoneBigMemoryConsumer* instance;
}
//Usage.
SingletoneBigMemoryConsumer* obj = SingletoneBigMemoryConsumer::getInstance();
// You cannot create more SingletoneBigMemoryConsumer here.
// After 1 seconds usage, delete it to reduce memory usage.
delete obj;
// You can create an new one when needed later
The owner of an object needs access to the destructor to destroy it. If the constuctors are private, there must be some accessible function to create an object. If that function transferes the ownership of the constructed object to the caller ( for example return a pointer to a object on the free store ) the caller must have the right to access the destructor when he decides to delete the object.
Is it possible to create a class which could be constructed just one time? If you would try to create an other instance of it, a compile-time error should occure.
Instantiation is dynamic, at run time. Compilation errors are at compile time. So the answer is no, it's not possible to get a compilation error on any second instantiation.
You can however use a singleton, but do consider very carefully whether it's really needed.
The classes with only one instances are called singleton classess,
There are many ways to perform that. The simplest is shown below
class MySingleton
{
public:
static MySingleton& Instance()
{
static MySingleton singleton;
return singleton;
}
// Other non-static member functions
private:
MySingleton() {}; // Private constructor
MySingleton(const MySingleton&); // Prevent copy-construction
MySingleton& operator=(const MySingleton&); // Prevent assignment
};
Why compile error? You just need to implement Singleton design pattern, I think.
Look here
is there some approach to make singleton class initialize on programs stack (hence members variables also)?
I have tried following, both were failed:
1)
class CStack{
public:
void* getAlloc(long);
static CStack& Instance(){
static CStack theStack;
return theStack;
}
private:
bool _data[100];
CStack(){};
CStack(const CStack&);
CStack& operator=(const CStack&);
};
2)
class CStack{
public:
void* getAlloc(long);
static CStack* Instance();
private:
CStack(){};
CStack(CStack const&){};
CStack& operator=(CStack const&){};
static CStack* m_pInstance;
};
CStack* CStack::m_pInstance = NULL;
CStack* CStack::Instance(){
if (!m_pInstance) // Only allow one instance of class to be generated.
m_pInstance = new CStack;
return m_pInstance;
}
first failed due to non-placement new initialization(m_pInstance = new CStack;), second due to lazy initialization. Could, please, someone help me?
Thanks
The whole point of singleton is not to rely on when and where it is initialized. The first access would initialize the object, and all subsequent access would yield the same object.
If you put the object on the stack - it will be destructed when the stack is closed (you exit out of the scope), thus future accesses would yield either invalid or a different object, but not the same (as you're out of the scope for the same one).
Thus, by definition of singleton, it cannot be done.
Now, if you explain the problem you're trying to solve, someone may help you with solving it in some more sensible way.