473,385 Members | 1,506 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Singleton usage

Consider the classic singleton (from Thinking in C++):
-----------------------------------------------------
//: C10:SingletonPattern.cpp
#include <iostream>
using namespace std;

class Singleton {
static Singleton s;
int i;
Singleton(int x) : i(x) { }
Singleton& operator=(Singleton&); // Disallowed
Singleton(const Singleton&); // Disallowed
public:
static Singleton& instance() { return s; }
int getValue() { return i; }
void setValue(int x) { i = x; }
};
-----------------------------------------------------

I've read this type of singleton is often used to store the global
variables, but I don't have found a clear explanation.

An example:

if, in file main.cpp, I write

Singleton Singleton::s(47);
Singleton& s = Singleton::instance();

and, in foo1.cpp, I write

Singleton& s1 = Singleton::instance();

and in foo2.cpp I write

Singleton& s2 = Singleton::instance();
these instances (s, s1 and s2) are the same object, so all methods and
properties are shared???? Because Singleton::s is static, I suppose yes,
but I'm not sure...

thx,

Manuel

Jan 7 '06 #1
6 2250
Manuel wrote:
Consider the classic singleton (from Thinking in C++):
-----------------------------------------------------
//: C10:SingletonPattern.cpp
#include <iostream>
using namespace std;

class Singleton {
static Singleton s;
int i;
Singleton(int x) : i(x) { }
Singleton& operator=(Singleton&); // Disallowed
Singleton(const Singleton&); // Disallowed
public:
static Singleton& instance() { return s; }
int getValue() { return i; }
void setValue(int x) { i = x; }
};
-----------------------------------------------------

I've read this type of singleton is often used to store the global
variables, but I don't have found a clear explanation.

An example:

if, in file main.cpp, I write

Singleton Singleton::s(47);
Singleton& s = Singleton::instance();

and, in foo1.cpp, I write

Singleton& s1 = Singleton::instance();

and in foo2.cpp I write

Singleton& s2 = Singleton::instance();
these instances (s, s1 and s2) are the same object,
They are all _references_, and they do _refer_ to the same object, yes.
so all methods and
properties are shared????
Since they _refer_ to the same object, all "properties" are that of the
object to which they refer.
Because Singleton::s is static, I suppose
yes, but I'm not sure...


Yes. The implementation makes sure that (a) only one instance of that
class can ever be created in the program and (b) any time somebody wants
to use it, they are forced to use a _reference_ to that instance. That
is essentially the definition of a singleton.

V
Jan 7 '06 #2
Victor Bazarov wrote:
Yes. The implementation makes sure that (a) only one instance of that
class can ever be created in the program and (b) any time somebody wants
to use it, they are forced to use a _reference_ to that instance. That
is essentially the definition of a singleton.


Thank you very much!

Manuel
Jan 7 '06 #3
Victor Bazarov wrote:
Yes. The implementation makes sure that [...]

Another question.
The example in "Thinking in C++" is:
----------------------------------------
Singleton Singleton::s(47);

int main() {
Singleton& s = Singleton::instance();
cout << s.getValue() << endl;
Singleton& s2 = Singleton::instance();
s2.setValue(9);
cout << s.getValue() << endl;
} ///:~
----------------------------------------

Any particular reason the singleton init is out of main()?
It should be global even if declared into a function, right?

thx,

Manuel

Jan 7 '06 #4
Manuel wrote:
Victor Bazarov wrote:
Yes. The implementation makes sure that [...]

Another question.
The example in "Thinking in C++" is:
----------------------------------------
Singleton Singleton::s(47);

int main() {
Singleton& s = Singleton::instance();
cout << s.getValue() << endl;
Singleton& s2 = Singleton::instance();
s2.setValue(9);
cout << s.getValue() << endl;
} ///:~
----------------------------------------

Any particular reason the singleton init is out of main()?
It should be global even if declared into a function, right?


That's the requirement for static data members of any class.
If they are to be defined, they must be defined at the namespace
scope.

V
Jan 8 '06 #5

Manuel wrote:
Victor Bazarov wrote:
Yes. The implementation makes sure that [...]

Another question.
The example in "Thinking in C++" is:
----------------------------------------
Singleton Singleton::s(47);

int main() {
Singleton& s = Singleton::instance();
cout << s.getValue() << endl;
Singleton& s2 = Singleton::instance();
s2.setValue(9);
cout << s.getValue() << endl;
} ///:~
----------------------------------------

Any particular reason the singleton init is out of main()?
It should be global even if declared into a function, right?


Since s is a static inside of Singleton it has to be initialized. All
static variables must be initialized exactly once or you will get a
linker error (because the declaration is just that and the variable was
never defined).

Try it and see...

Jan 9 '06 #6
Manuel wrote:
Consider the classic singleton (from Thinking in C++):
-----------------------------------------------------
//: C10:SingletonPattern.cpp
#include <iostream>
using namespace std;

class Singleton {
static Singleton s;
int i;
Singleton(int x) : i(x) { }
Singleton& operator=(Singleton&); // Disallowed
Singleton(const Singleton&); // Disallowed
public:
static Singleton& instance() { return s; }
int getValue() { return i; }
void setValue(int x) { i = x; }
};
-----------------------------------------------------

I've read this type of singleton is often used to store the global
variables, but I don't have found a clear explanation.


Be aware, that if the above singleton is called from another global
object during initialization that's in a different translation unit,
than it can, and most likely will fail.

There's no garantee for the order of initialization of global complex
objects located in different translation units.
See following links:
http://www.informit.com/guides/conte...eqNum=212&rl=1

And read SECOND paragraph in the following link:
http://www.codeguru.com/cpp/tic/tic0114.shtml
A safer method would be the following:
class Singleton {
static const int m_MySingletonParam;
int i;
Singleton(int x) : i(x) { }
Singleton& operator=(Singleton&); // Disallowed
Singleton(const Singleton&); // Disallowed
public:
static Singleton& instance()
{
static Singleton s(m_MySingletonParam);
return s;
}
int getValue() { return i; }
void setValue(int x) { i = x; }
};

//In one CPP file
const int Singleton::m_MySingletonParam = 123;
The above method is garanteed to work, because POD types are garanteed
to be initailized before non-POD types. And local static variables are
garanteed to be initialized when the function is called.
So you can safely call the above Singleton from any other global
object's constructor, regardless of the translation unit.

If it's possible that the singlton will be called after main() exits,
then you should create the object via new, to make sure it doesn't get
destroyed before othe global object's destructs are called.
static Singleton& instance()
{
static Singleton *s = new Singleton (m_MySingletonParam);
return *s;
}

Jan 9 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Tim Clacy | last post by:
Is there such a thing as a Singleton template that actually saves programming effort? Is it possible to actually use a template to make an arbitrary class a singleton without having to: a)...
3
by: Alicia Roberts | last post by:
Hello everyone, I have been researching the Singleton Pattern. Since the singleton pattern uses a private constructor which in turn reduces extendability, if you make the Singleton Polymorphic...
5
by: LinuxGuy | last post by:
Hi, I have come across singleton class with some member variables are declared as static with public scope. As singleton class always return only one instance. ie. single copy of object is ...
7
by: Stephen Brown | last post by:
I have some strange behavior on my web server that seems to point to garbage collection. I have a singleton that tracks web activity on my web site. The singleton works great, except that it...
21
by: Sharon | last post by:
I wish to build a framework for our developers that will include a singleton pattern. But it can not be a base class because it has a private constructor and therefore can be inherit. I thought...
3
by: Jeremy Cowles | last post by:
Will the keyword "Me" ever be able to be the target of an assignment? Because singleton classes would be MUCH simplier if you could just point Me to a different address. For example: Class...
15
by: Nick Keighley | last post by:
Hi, I found this in code I was maintaining template <class SingletonClass> SingletonClass* Singleton<SingletonClass>::instance () { static SingletonClass _instance; return &_instance; }
12
by: keepyourstupidspam | last post by:
Hi, I am writing a windows service. The code runs fine when I start the service when my machine is running but it fails to start automatically when the machine reboots. The code bombs out when...
7
by: fredd00 | last post by:
Hi I'm just starting with singleton and would like to implement in my new web app. I have a question lets say i create a singleton DataHelper that holds a static SqlConnection object to...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.