473,785 Members | 2,789 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ singleton pattern question

Hi

Could someone tell me what's the difference between these two singleton
implementations :

First implementation:

class Singleton
{
public:
static Singleton& instance() { return _instance; }
//... other members
private:
Singleton();
static Singleton _instance;
//... other members
};

Second implementation:

class Singleton
{
public:
static Singleton* instance() { return _instance; }
static void Initialize() { _instance = new Singleton; }
//... other members
private:
Singleton();
static Singleton* _instance;
//... other members
};

I know that in the first implementation, _instance will be put in the
static memory, and it will always be present, whereas in the second
implementation, memory will only be allocated on the heap after
Singleton::Init ialize() is called. But aside from that, is there any
practical difference between the two, like on what circumstances is the
first implementation preferred over the second (or vice versa)?

Thanks!

Jul 23 '05 #1
10 5310
For one thing, the pointer implementation has no clean up code - so any
resources the singleton uses may not be returned.

regards,

Aiden
<fe************ ****@gmail.com> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
Hi

Could someone tell me what's the difference between these two singleton
implementations :

First implementation:

class Singleton
{
public:
static Singleton& instance() { return _instance; }
//... other members
private:
Singleton();
static Singleton _instance;
//... other members
};

Second implementation:

class Singleton
{
public:
static Singleton* instance() { return _instance; }
static void Initialize() { _instance = new Singleton; }
//... other members
private:
Singleton();
static Singleton* _instance;
//... other members
};

I know that in the first implementation, _instance will be put in the
static memory, and it will always be present, whereas in the second
implementation, memory will only be allocated on the heap after
Singleton::Init ialize() is called. But aside from that, is there any
practical difference between the two, like on what circumstances is the
first implementation preferred over the second (or vice versa)?

Thanks!


Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com
Jul 23 '05 #2
Yes, but let's say I add another method, say CleanUp(), in the second
implementation that deletes _instance, and users are required to call
Initialize and CleanUp before and after using the class, respectively.
Are the first and second now functionally identical? Or is there a
situation where one implementation is better than the other? (e.g. in a
multi-threaded application, etc.)?

Jul 23 '05 #3
Apart from the explicit vs implicit memory management there is no real
difference - as far as multi - threading is concerned, you need to employ
some synchronisation primitives to protect simulataneous access to your
singleton - the same situation exists in both cases.

The 'popular' issue with threading, is a third possibile implementation
whereby:
MySingleton * instance()
{
static MySingleton * pInst = new MySingleton();

return pInst;
}

That changes your synchronisation requirements - but how is very dependent
on your particular design/usage.

hope that helps,

regards,
Aiden

<fe************ ****@gmail.com> wrote in message
news:11******** *************@o 13g2000cwo.goog legroups.com...
Yes, but let's say I add another method, say CleanUp(), in the second
implementation that deletes _instance, and users are required to call
Initialize and CleanUp before and after using the class, respectively.
Are the first and second now functionally identical? Or is there a
situation where one implementation is better than the other? (e.g. in a
multi-threaded application, etc.)?


Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com
Jul 23 '05 #4
Apart from the explicit vs implicit memory management there is no real
difference - as far as multi - threading is concerned, you need to employ
some synchronisation primitives to protect simulataneous access to your
singleton - the same situation exists in both cases.

The 'popular' issue with threading, is a third possibile implementation
whereby:
MySingleton * instance()
{
static MySingleton * pInst = new MySingleton();

return pInst;
}

That changes your synchronisation requirements - but how is very dependent
on your particular design/usage.

hope that helps,

regards,
Aiden

<fe************ ****@gmail.com> wrote in message
news:11******** *************@o 13g2000cwo.goog legroups.com...
Yes, but let's say I add another method, say CleanUp(), in the second
implementation that deletes _instance, and users are required to call
Initialize and CleanUp before and after using the class, respectively.
Are the first and second now functionally identical? Or is there a
situation where one implementation is better than the other? (e.g. in a
multi-threaded application, etc.)?


Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com
Jul 23 '05 #5
Apart from the explicit vs implicit memory management there is no real
difference - as far as multi - threading is concerned, you need to employ
some synchronisation primitives to protect simulataneous access to your
singleton - the same situation exists in both cases.

The 'popular' issue with threading, is a third possibile implementation
whereby:
MySingleton * instance()
{
static MySingleton * pInst = new MySingleton();

return pInst;
}

That changes your synchronisation requirements - but how is very dependent
on your particular design/usage.

hope that helps,

regards,
Aiden

<fe************ ****@gmail.com> wrote in message
news:11******** *************@o 13g2000cwo.goog legroups.com...
Yes, but let's say I add another method, say CleanUp(), in the second
implementation that deletes _instance, and users are required to call
Initialize and CleanUp before and after using the class, respectively.
Are the first and second now functionally identical? Or is there a
situation where one implementation is better than the other? (e.g. in a
multi-threaded application, etc.)?


Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com
Jul 23 '05 #6
Apart from the explicit vs implicit memory management there is no real
difference - as far as multi - threading is concerned, you need to employ
some synchronisation primitives to protect simulataneous access to your
singleton - the same situation exists in both cases.

The 'popular' issue with threading, is a third possibile implementation
whereby:
MySingleton * instance()
{
static MySingleton * pInst = new MySingleton();

return pInst;
}

That changes your synchronisation requirements - but how is very dependent
on your particular design/usage.

hope that helps,

regards,
Aiden

<fe************ ****@gmail.com> wrote in message
news:11******** *************@o 13g2000cwo.goog legroups.com...
Yes, but let's say I add another method, say CleanUp(), in the second
implementation that deletes _instance, and users are required to call
Initialize and CleanUp before and after using the class, respectively.
Are the first and second now functionally identical? Or is there a
situation where one implementation is better than the other? (e.g. in a
multi-threaded application, etc.)?


Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com
Jul 23 '05 #7
adbarnet wrote:
Apart from the explicit vs implicit memory management there is no real
difference - as far as multi - threading is concerned, you need to employ
some synchronisation primitives to protect simulataneous access to your
singleton - the same situation exists in both cases.

The 'popular' issue with threading, is a third possibile implementation
whereby:
MySingleton * instance()
{
static MySingleton * pInst = new MySingleton();

return pInst;
}

....

Doing is this way, with a static 'inside' a function guarantees that
MySingleton will be initialised even if you try and access it before
main() is called. e.g from another singleton, or initialisation.
Jul 23 '05 #8
Ok, just to be complete, lets add the fourth implementation

class Singelton
{
Singelton();

public:

static Singelton& Instance() { static Singelton s; return s; }
};

cheers
Jul 23 '05 #9
fe************* ***@gmail.com wrote:
Yes, but let's say I add another method, say CleanUp(), in the second
implementation that deletes _instance, and users are required to call
Initialize and CleanUp before and after using the class, respectively.
Are the first and second now functionally identical? Or is there a
situation where one implementation is better than the other? (e.g. in a
multi-threaded application, etc.)?


Read up on the "static initialization order fiasco" in this newsgroup's FAQ.

Jul 23 '05 #10

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

Similar topics

1
2038
by: Richard A. DeVenezia | last post by:
foo() generates elements with event handlers that invoke foo function properties. Is this an abhorrent or misthought pattern ? It allows just the one occurence of identifier /foo/ to be changed to /whatever/ when need arises and everything should still work. function foo () { var callee = arguments.callee
2
2723
by: Simon | last post by:
Hi. I don't have a problem per se, I was just wondering if anyone can offer some opinions about the best way to go about creating and disposing of a Singleton class. I have a class (handling DB connections) which I have defined as a singleton, using the following pattern (VB.net code) Private Shared mInstance As clsConnection = Nothing
4
8243
by: Eric | last post by:
Perhaps this question has been posed before (I'd be surprised if it hasn't) but I just gotta know... Is it possible to combine the Singleton and Factory Method design patterns in the same class? Let's start with your basic Singleton class: class Singleton {
3
2499
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 what sort of problems/issues should be considered? Also, I see that a singleton needs to be set up with certain data such as file name, database URL etc. What issues are involved in this, and how would you do this? If someone knows about the...
21
2469
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...
8
2822
by: Gaensh | last post by:
HI, I have a singleton pattern to acess my database the following is the sample code use to implement singleton pattern public class DataAccessHelper { private static DataAccessHelper instance; /// <summary> /// public property that can only get the single instance of this class. /// </summary>
2
6348
by: Kevin Newman | last post by:
I have been playing around with a couple of ways to add inheritance to a JavaScript singleton pattern. As far as I'm aware, using an anonymous constructor to create a singleton does not allow any kind of inheritance: singletonObj = new function() { this.prop = true; } Here are two ways to create a singleton with inheritance:
5
1609
by: Diffident | last post by:
Hello All, I am designing a class based on singleton pattern. Inside this class I have multiple instance methods. My question is since there will be only one instance of this class at any instance of time in the whole application there is no use in having these methods as instance methods I can as well have static methods....correct? If I leave these methods as instance methods would they have any wrong impact on my application?
3
18253
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That is, regardless of where the object is hidden, everyone needs access to it. The global point of access is the object's Instance() method. Individual users need to be prevented from creating their own instances of the Singleton.
2
1590
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...
0
9645
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
10336
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10095
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
8978
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7502
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
6741
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();...
0
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3655
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.