473,856 Members | 1,713 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

singleton class problem

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 access and life is restricted within the thread, then a static
initialization is safe ?

Thanks
abir

Nov 30 '06 #1
6 3201
* toton:
Hi,
If I have a singleton class based on dynamic initialization (with new
) , is it considered a memory leak?
Generally the term "memory leak" refers to /repeated/ memory allocations
without corresponding deallocations, a worsening over time.

Anything in C++ standard says about it ?
No, it doesn't define "memory leak".

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?
Both, although the current C++ standard does not address threading issues.

However, take a look at Boost's thread local storage class.

If the singleton is per thread basis (then no more singleton though
), and access and life is restricted within the thread, then a static
initialization is safe ?
Define what you mean by "safe", best with some actual code.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 30 '06 #2
toton wrote:
If I have a singleton class based on dynamic initialization (with new
) , is it considered a memory leak?
If you maintain a pointer to every dynamically allocated region of
memory, there is no leak. A leak occurs when you have allocated memory
or another resource and no longer have a pointer/handle to it.

I got this definition from one of Scott Meyers' books, and it seems
pretty good to me.

Nate
Nov 30 '06 #3

toton wrote:
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 ?
Yes, its a memory leak. What that entails is undefined. However, there
is no excuse for such a condition since a simple singleton using a
shared_ptr is the way to go. There are other benefits that some
shared_ptrs brings to the picture as well (ie: boost::shared_p tr). Read
some of the Posts here to find out what those are.
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?
All statics are affected by access if you use threads. That too has a
simple solution. write a class that locks / unlocks for you.
If the singleton is per thread basis (then no more singleton though
), and access and life is restricted within the thread, then a static
initialization is safe ?
Ask in an appropriate newsgroup that does threads.
Typically, static variables have internal linkage. In C++ thats
considered deprecated. A better alternative is to use statics in
namespaces or even in anonymous namespaces.

namespace whatever
{
static int n = 99;
static create() { ... }
}

Such a strategy is better design since a static variable named var in
one file is not the same static var in another. internal linkage =
static file linkage.

Nov 30 '06 #4
Hi,

If you are working with multithreading then Singleton implemention will
have problem if you are not using locking mechanism.Two or more thead
might be accessing Static function and crate more then one instance of
Singleton class. But locking will hit performance. So double check
locking is advised.
You can get more informaton ragarding doublechecked locking
http://www.cs.umd.edu/~pugh/java/mem...edLocking.html

Nov 30 '06 #5

Salt_Peter wrote:
toton wrote:
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 ?

Yes, its a memory leak.
Confused :(
Got two answer, one says yes the other no!
I always get two opposite answers for a question related to C++.
It is a memory leak from program's point of view. But doesn't OS cleans
the memory ?
What happens when I run new based singleton class several times. Will
the OS consume all
of the system memory (RAM) ?
confused again, and leaving the topic here (as, because people will say
it is off topic :( ).
>What that entails is undefined. However, there
is no excuse for such a condition since a simple singleton using a
shared_ptr is the way to go. There are other benefits that some
shared_ptrs brings to the picture as well (ie: boost::shared_p tr). Read
some of the Posts here to find out what those are.
Not sure how shared_ptr will be able to do it from outside. Searching
the newsgroup is not giving any hint.
So to have a second way, I have a near-singleton class. Which I know
standard enough so that no one creates a duplicate one (by convention,
not by design) . It is just a regular class and has a virtual
destruction, which gets called in program termination. In my case, it
is QApplication from Qt.
Now I have a few other "singleton class" by design. i.e they have
private ctor, copy ctor and copy assignment operator.
Now If I remove the singleton static pointer & get method, and make
them friend of QApplication (it is just a class in this context, not
off topic as it is a Qt class). and add them as member of QApplication.
Then I can delete them in usual way (with shared ptr or move_ptr or
even simple raw ptr) in QApplication destructor.
So, I don't have the problem of having multiple instance of those
"pseudo singleton classes", while only a single instance of
QApplication will keep track of it.
Anyone do this kind of thing (i.e clubbing several non-constructible,
non-copyable, non assignable classes, with a friend class, which has
the role of constructing & destructing them)
May be it is little similar to the Stroustrup's way of making a final
class.
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?

All statics are affected by access if you use threads. That too has a
simple solution. write a class that locks / unlocks for you.
here i have doubt about static linkage. What it actually refers ?
unlike object ,class members (i.e static members ) are one per class (i
or per class / per thread or something else). i.e for static only one
"memory location" (may not be an appropriate term, but hope conveys the
meaning) location per application ( or per thread ? ) If it is per
application, then not a problem for me, but otherwise yes. i.e my
requirement is, anywhere from the application &my_class::my_s tatic_var
to return same value, irrespective of thread or anything else.
If the singleton is per thread basis (then no more singleton though
), and access and life is restricted within the thread, then a static
initialization is safe ?

Ask in an appropriate newsgroup that does threads.
Typically, static variables have internal linkage. In C++ thats
considered deprecated. A better alternative is to use statics in
namespaces or even in anonymous namespaces.

namespace whatever
{
static int n = 99;
static create() { ... }
}

Such a strategy is better design since a static variable named var in
one file is not the same static var in another. internal linkage =
static file linkage.
Nov 30 '06 #6
"toton" <ab*******@gmai l.comwrote in
news:11******** **************@ h54g2000cwb.goo glegroups.com:
>
Salt_Peter wrote:
>toton wrote:
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 ?

Yes, its a memory leak.
Confused :(
Got two answer, one says yes the other no!
I always get two opposite answers for a question related to C++.
It is a memory leak from program's point of view. But doesn't OS
cleans the memory ?
What the OS does with the allocated memory after the program ends isn't
C++'s problem. So strictly speaking, I would say that you have a memory
leak in your program. Your object was not deleted by you. Perhaps
wrapping it into a smart pointer of some description (std::auto_ptr ?).
What happens when I run new based singleton class several times. Will
the OS consume all
of the system memory (RAM) ?
Huh? How do you "run new based singleton class serveral times"? If you
can have multiple instances of the object, it's not a singleton
anymore....

Nov 30 '06 #7

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

Similar topics

2
2745
by: Rajarshi Guha | last post by:
Hi, I'm having a little problem with understanding the working of a singleton and borg class. Basically I nedd an class whose state will be shared across several modules. I found the stuff on the ASPN cookbook but it does'nt seem to be working for me. I've included some code: Borg.py: -------- class Borg: __shared_state = {} def __init__(self):
16
6743
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
2456
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
3933
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
5
5382
by: tobias.sturn | last post by:
Hi! I have written this template for making a singleton: #define DECLARE_SINGLETON(classname) \ private: \ static classname* m_pThis; \ classname(); \ class Guard \ { \ public: \
3
2972
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
2
1592
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...
5
2116
by: Lie | last post by:
This is probably unrelated to Python, as this is more about design pattern. I'm asking your comments about this design pattern that is similar in functionality to Singleton and Borg: to share states. I'm thinking about this design pattern (I don't know if anyone has ever thought of this pattern before): class OddClass(object): def __init__(self): global OddClass
4
2833
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
9916
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
9762
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,...
0
11057
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...
0
10696
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9531
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
7932
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
7094
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
5958
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4174
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.