473,804 Members | 2,296 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ Singleton problem...

Hi!

I have written this template for making a singleton:
#define DECLARE_SINGLET ON(classname) \
private: \
static classname* m_pThis; \
classname(); \
class Guard \
{ \
public: \
~Guard() \
{ \
if(classname::m _pThis != 0 ) \
delete classname::m_pT his; \
} \
}; \
friend class Guard; \
public: \
static classname* getInstance();

#define DEFINE_SINGLETO N(classname) \
classname* classname::m_pT his=0; \
classname* classname::getI nstance() \
{ \
static Guard guard; \
if(m_pThis == 0) \
{ \
m_pThis = new classname(); \
} \
return m_pThis; \
}

Now i have a class which uses these macros but now i still i can write
constructors make them public and i have won nothing...

class Class
{
public:
Class(int a) {/*i have created an object :(*/
Class(char a)...
};;

How could i make it not possible for the user of the template that he
cant override the constructor?

Thanks very much!!

Jun 15 '06 #1
5 5380
tobias.sturn wrote:
Now i have a class which uses these macros but now i still i can write
constructors make them public and i have won nothing...

class Class
{
public:
Class(int a) {/*i have created an object :(*/
Class(char a)...
};;
You can't. The point of classes is to be upgraded and re-used. Deal.
How could i make it not possible for the user of the template that he
cant override the constructor?


The mininimal situation worked for me:

class frob {
DECLARE_SINGLET ON(frob);
};

DEFINE_SINGLETO N(frob);
frob::frob() {}
#include <assert.h>
#include <stdlib.h>

int main()
{
frob * pFrob = frob::getInstan ce();
assert(NULL != pFrob);
// frob aFrob; // <-- bad
return 0;
}

Now about your style. "Singleton" is the most abused pattern in /Design
Patterns/, and it's the best candidate for time travel to tell the GOF to
take it out. I can think of many situations where a program needs only one
of something, but I can't think of any situation where a program should
never have more than one of something.

Next, you should use unit tests (like my main()), and should pass them after
every edit. This implies that some of your classes should use a mock object
instead of your singleton. So that implies that tests have legitimate
reasons to re-use more than one instance of your singleton, to construct
them with extra data, and to derive from them.

Next, a Singleton is not an excuse for a global variable. Most clients of
your singleton should pass it in by reference. They should not rely on it
floating around in space. So nearly all clients of your singleton should
accept a reference that your tests can mock.

Next, you are abusing macros. You should instead abuse templates. Google for
[c++ singleton template], and get sample code like this:

http://www.codeproject.com/cpp/singleton_template.asp

Next, neither your getInstance() nor the one on that page can return a NULL
pointer, so they should return a reference to the Singleton. Whichever
pattern you go with, make that small fix.

Next, I suspect this is the best implementation for the getter:

static T& Instance()
{
static T aT;
return aT;
};

That is well-defined to construct aT at least before the first time the
function enters, so it fixes the common C++ problem with global variables
constructing out of order, and fixes it without the odious choice of a 'new'
call. Other patterns and situations may easily apply here, too.

After applying any subset of my suggestions, you will have a better program
with less need to restrict your constructors.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
Jun 16 '06 #2

to**********@vo l.at wrote:
Hi!

I have written this template for making a singleton:
#define DECLARE_SINGLET ON(classname) \
private: \
static classname* m_pThis; \
classname(); \
class Guard \
{ \
public: \
~Guard() \
{ \
if(classname::m _pThis != 0 ) \
delete classname::m_pT his; \
} \
}; \
friend class Guard; \
public: \
static classname* getInstance();

#define DEFINE_SINGLETO N(classname) \
classname* classname::m_pT his=0; \
classname* classname::getI nstance() \
{ \
static Guard guard; \
if(m_pThis == 0) \
{ \
m_pThis = new classname(); \
} \
return m_pThis; \
}

Now i have a class which uses these macros but now i still i can write
constructors make them public and i have won nothing...

class Class
{
public:
Class(int a) {/*i have created an object :(*/
Class(char a)...
};;

How could i make it not possible for the user of the template that he
cant override the constructor?

Thanks very much!!


With the following Singleton class, you can create a Singleton use one
of two methods.
You can derive from Singleton as the foo example class does below, or
you can create a class like the Widget example class.

template<typena me T>
class Singleton
{
protected:
Singleton(){}
~Singleton(){}
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
public:
class FriendClass
{
public:
FriendClass():m _MyClass(new T()){}
~FriendClass(){ delete m_MyClass;}
T* m_MyClass;
};
static T& Instance() {
static FriendClass Instance;
return *Instance.m_MyC lass;
}
};

class Widget {
private:
Widget(){}
~Widget(){}
Widget& operator=(const Widget&);
Widget(const Widget&);
public:
friend class Singleton<Widge t>::FriendClass ;
int m_i;
};
class foo : public Singleton<foo>{
private:
foo(){}
~foo(){}
foo& operator=(const foo&);
foo(const foo&);
public:
friend class FriendClass;
int m_i;
};
int main(int argc, char* argv[])
{
Widget& MyWidget = Singleton<Widge t>::Instance() ;
foo& Myfoo = foo::Instance() ;

system("pause") ;
return 0;
}

Jun 16 '06 #3
Axter wrote:

You answered the wrong question. (I do that often enough I'm going to
crack down on you for it.)
class Widget {
private:
Widget(){}
~Widget(){}


One can still write 'public: Widget(somethin g)' here, and construct the
Widget without the Singleton wrapper.

--
Phlip
Jun 16 '06 #4

Phlip wrote:
Axter wrote:

You answered the wrong question. (I do that often enough I'm going to
crack down on you for it.)
class Widget {
private:
Widget(){}
~Widget(){}


One can still write 'public: Widget(somethin g)' here, and construct the
Widget without the Singleton wrapper.


Then you would not be creating a Singleton.
Widget is the target Singleton. When you create a Singleton, you want
your constructors to be private.

Jun 18 '06 #5
Axter wrote:
Then you would not be creating a Singleton. Widget is the target
Singleton. When you create a Singleton, you want your constructors to be
private.


That's the design answer (which I already provided). The technical answer
is you can't prevent Widget from having other constructors.

--
Phlip
Jun 18 '06 #6

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

Similar topics

16
6738
by: cppaddict | last post by:
Hi, In this tutorial on singleton class in C++ (http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp) the author gives two implementations of a simple singleton class, claiming that only the first is safe for multi-threaded appliactions. I want to know why this so. The class is as follows:
1
2454
by: Jim Strathmeyer | last post by:
So I'm trying to implement a singleton template class, but I'm getting a confusing 'undefined reference' when it tries to link. Here's the code and g++'s output. Any help? // singleton.h template <class T> class Singleton : public T { public: static T * Instance();
3
3930
by: Harry | last post by:
Hi ppl I have a doubt on singleton class. I am writing a program below class singleton { private: singleton(){}; public: //way 1
7
3619
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 restarts periodically. The web services have not been restarted and the error log shows no problems. It is the same problem on 2 different servers, but is worse on the most used server. On the most used server, it gets restarted 5 to 10 times a day...
21
2472
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 maybe a Template can be use for that, but C# does not support Templates (will be C# generics in mid 2005). Does anyone have a solution on how the singleton pattern can be written, in C#, as a framework/ infrastructure class, so users can use this...
3
2968
by: dischdennis | last post by:
Hello List, I would like to make a singleton class in python 2.4.3, I found this pattern in the web: class Singleton: __single = None def __init__( self ): if Singleton.__single: raise Singleton.__single
6
3198
by: toton | last post by:
Hi, If I have a singleton class based on dynamic initialization (with new ) , is it considered a memory leak? Anything in C++ standard says about it ? And little off - topic question , If the singleton is initialized as a static variable , it seems there is some threading issue . Is it the issue during singleton initialization only , or during the access also? If the singleton is per thread basis (then no more singleton though ), and...
3
435
by: wizwx | last post by:
There are two typical implementations of a singleton. The first one is to use a static pointer class Singleton { static Singleton * pSingleton; public: Singleton * instance() { if(pSingleton==NULL) pSingleton = new Singleton; return pSingleton; }
2
1591
by: Bob Johnson | last post by:
Just wondering the extent to which some of you are implementing classes as Singletons. I'm working on a brand new project and, early on, identified some obvious candidates. By "obvoius candidates" I mean classes for which terrible problems would clearly arise if more than one instance were to exist. But as I'm getting into the design of this new solution, I'm realizing that a large percentage of the classes _could be_ implemented as...
4
2828
by: John Doe | last post by:
Hi, I have a singleton class defined like this : class UIManager : public CSingleton<UIManager>, public CObject { protected: DECLARE_DYNAMIC(UIManager) friend class CSingleton<UIManager>;
0
9714
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10347
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10090
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7635
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6863
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3832
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.