Please suggest me the link or sample code for the singleton method.
1) Need to create single instance and need to use that instance in entire project.
2) Should not allow to create new instance.
Code:
#include <stdio.h>
#include <iostream>
using namespace std;
class Sample
{
private:
int test;
public:
int setValue(int a)
{
test=a;
}
int getValue()
{
cout<<"test value = "<<test;
}
};
class CMySingleton
{
private:
CMySingleton() {};
static Sample *singleton;
public:
static Sample* Instance()
{
singleton=new Sample();
return singleton;
}
};
int main()
{
Sample *obj=CMySingleton::Instance();
cout<<"\n "<<&obj;
Sample *obj1=CMySingleton::Instance();
cout<<"\n "<<&obj1;
return 0;
}
It throws error
/tmp/ccFuSDhv.o: In function `CMySingleton::Instance()':
singleton.cpp.text._ZN12CMySingleton8InstanceEv[CMySingleton::Instance()]+0x17): undefined reference to `CMySingleton::singleton'
singleton.cpp.text._ZN12CMySingleton8InstanceEv[CMySingleton::Instance()]+0x1e): undefined reference to `CMySingleton::singleton'
Here it gets initialized on first call, and gets automatically destroyed properly when the program exits. It also eliminates the need for a global.
Err... with an extra static in there... right?
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
There are as many ways to write a singleton as fingers on your hand. Don't worry about it too much, as long as you have something working.
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Are you singling out my implementation specifically? Because the entire pattern is not thread safe, so its not like there's an alternative.
Last edited by monarch_dodra; May 3rd, 2012 at 10:22 AM.
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
The static one is thread safe in C++11 if I don't remember wrong.
Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it.
- Brian W. Kernighan
The static one is thread safe in C++11 if I don't remember wrong.
You are right:
§ 6.7.4
.. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
Bookmarks