473,883 Members | 1,798 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

mem leak in Singleton?

Hi,

I have a class defined as a "Singleton" (Design Pattern). The codes are
attached below.
My questions are:
1. Does it has mem leak? If no, when did the destructor called? If yes, how
can I avoid it? Purify does not show it has mem leak.

// test if singleto class has mem leakage
#include <iostream>
using namespace std;

class Singleton {
public:
static Singleton* Instance();
~Singleton();
void print();
protected:
Singleton();
private:
static Singleton* _instance;
double* test;
};

Singleton* Singleton::_ins tance = 0;

Singleton::Sing leton() {
test = new double[10];
for (int i=0; i<10; i++) test[i] = i;
}

Singleton::~Sin gleton() {
cout << "Destructor called!" << endl;
if (test) delete [] test; //
*************** **************
}

Singleton*
Singleton::Inst ance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}

void
Singleton::prin t() {
for (int i=0; i<10; i++) cout << test[i] << endl;
}

int main() {
Singleton::Inst ance()->print();
}
2. If I remove the line marked "//*********" in the destructor, purify still
shows no mem leak!!!! Obviously this is since "test" was not deleted.

Anybody has some answers?

Thanks,
Jul 22 '05 #1
7 3296
Ethan wrote:
Hi,

I have a class defined as a "Singleton" (Design Pattern). The codes are
attached below.
My questions are:
1. Does it has mem leak? If no, when did the destructor called? If yes, how
can I avoid it? Purify does not show it has mem leak.

// test if singleto class has mem leakage
#include <iostream>
using namespace std;

class Singleton {
public:
static Singleton* Instance();
~Singleton();
void print();
protected:
Singleton();
private:
static Singleton* _instance;
Do not start your members with an underscore,
leave those nomenclatures to the implementation.
double* test;
};

Singleton* Singleton::_ins tance = 0;

Singleton::Sing leton() {
test = new double[10];
for (int i=0; i<10; i++) test[i] = i;
}

Singleton::~Sin gleton() {
cout << "Destructor called!" << endl;
if (test) delete [] test; //
Are you making the assumption that test would be set to null,
if new fails in the constructor. 'new' throws 'std::bad_alloc '
in case of failure.
Singleton::Sing leton() {
try {
test = new double[10];
allocated = true;
for (int i=0; i<10; i++) test[i] = i;
} catch (const std::bad_alloc & e) {
allocated = false;
}
}

Singleton::~Sin gleton() {
cout << "Destructor called!" << endl;
if (allocated) delete [] test;
}

add the member variable 'allocated' to
the class definition.
*************** **************
}

Singleton*
Singleton::Inst ance() {
if (_instance == 0) {
_instance = new Singleton;
}
As a simple rule-of-thumb try to have your new / delete
close to each other as far as possible.
return _instance;
}

void
Singleton::prin t() {
for (int i=0; i<10; i++) cout << test[i] << endl;
}

int main() {
Singleton::Inst ance()->print();


You have a got a unnamed temporary pointer object,
pointing to a 'Singleton' object and you are not freeing it.
This is a memory leak.
Jul 22 '05 #2
>>
class Singleton {
public:
static Singleton* Instance();
~Singleton();
void print();
protected:
Singleton();
private:
static Singleton* _instance;


Do not start your members with an underscore,
leave those nomenclatures to the implementation.


That is misleading advice, the name used is perfectly valid (as I suspect
you know).

john
Jul 22 '05 #3

"Ethan" <bo*******@gmai l.com> wrote in message
news:41******** @news.cadence.c om...
Hi,

I have a class defined as a "Singleton" (Design Pattern). The codes are
attached below.
My questions are:
1. Does it has mem leak? If no, when did the destructor called? If yes,
how
can I avoid it? Purify does not show it has mem leak.


No the destructor is never called. Whether this is a memory leak depends on
how you define memory leak. I've never heard of an operating system that
doesn't reclaim all allocated memory when a program exits.

john
Jul 22 '05 #4

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:2v******** *****@uni-berlin.de...
| >>
| >> class Singleton {
| >> public:
| >> static Singleton* Instance();
| >> ~Singleton();
| >> void print();
| >> protected:
| >> Singleton();
| >> private:
| >> static Singleton* _instance;
| >
| > Do not start your members with an underscore,
| > leave those nomenclatures to the implementation.
|
| That is misleading advice, the name used is perfectly valid (as I suspect
| you know).

I don't know how you think it's misleading ?

No where in that sentence can I see a suggestion
that their use here is *invalid*.

I happen to agree with the advice, btw - I find
those identifiers to be very ugly and confusing
to read.

Cheers.
Chris Val
Jul 22 '05 #5
John Harrison wrote:
class Singleton {
public:
static Singleton* Instance();
~Singleton();
void print();
protected:
Singleton();
private:
static Singleton* _instance;


Do not start your members with an underscore,
leave those nomenclatures to the implementation.

That is misleading advice, the name used is perfectly valid (as I suspect
you know).


I did not say it is invalid. That was more of a comment on the
style. Somehow when I read a piece of code, and if I see a symbol
starting with an underscore, I take it to be a predefined symbol
(either by the standard or by the implementation) . But then, that
could be me ..
Jul 22 '05 #6

"Karthik Kumar" <ka************ *******@yahoo.c om> wrote in message
news:418c9bbb$1 @darkstar...
John Harrison wrote:
class Singleton {
public:
static Singleton* Instance();
~Singleton();
void print();
protected :
Singleton();
private:
static Singleton* _instance;

Do not start your members with an underscore,
leave those nomenclatures to the implementation.

That is misleading advice, the name used is perfectly valid (as I suspect
you know).


I did not say it is invalid. That was more of a comment on the
style. Somehow when I read a piece of code, and if I see a symbol
starting with an underscore, I take it to be a predefined symbol
(either by the standard or by the implementation) . But then, that
could be me ..


If you are making style comments then I think you should say something like
'It's a bad idea to ...', 'Do not' is too categorical for a style comment,
it makes it sound as if you are saying something is an error.

I think that the OP usage of underscores is perfectly OK, even a good idea.
So for just about every style issue there are contrary opinions, which is
why I think you should be careful to distinguish between style issues and
language issues.

john
Jul 22 '05 #7

"Ethan" <bo*******@gmai l.com> wrote in message
news:41******** @news.cadence.c om...
Hi,

I have a class defined as a "Singleton" (Design Pattern). The codes are
attached below.
My questions are:
1. Does it has mem leak? If no, when did the destructor called? If yes,
how
can I avoid it? Purify does not show it has mem leak.

// test if singleto class has mem leakage
#include <iostream>
using namespace std;

class Singleton {
public:
static Singleton* Instance();
~Singleton();
void print();
protected:
Singleton();
private:
static Singleton* _instance;
double* test;
};

Singleton* Singleton::_ins tance = 0;

Singleton::Sing leton() {
test = new double[10];
for (int i=0; i<10; i++) test[i] = i;
}

Singleton::~Sin gleton() {
cout << "Destructor called!" << endl;
if (test) delete [] test; //
*************** **************
}

Singleton*
Singleton::Inst ance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}

void
Singleton::prin t() {
for (int i=0; i<10; i++) cout << test[i] << endl;
}

int main() {
Singleton::Inst ance()->print();
}
2. If I remove the line marked "//*********" in the destructor, purify
still
shows no mem leak!!!! Obviously this is since "test" was not deleted.


The destructor was never called. The memory will be reclaimed at the end
of the program, so this really isn't a memory leak. If you need the
destructor to be called (to do logging for instance), the way I always do it
is to add a new private member function
static void cleanup();

Define cleanup() as

void Singleton::clea nup()
{
delete _instance;
_instance = 0;
}

Then change your instance() function to as follows:

Singleton *Singleton::Ins tance() {
if (_instance == 0) {
_instance = new Singleton;
atexit(cleanup) ; //Guarantee the Singleton will be deleted after
main() returns.
}
return _instance;
}

This guarantees that your destructor will be called. Note that this is
unsafe if the Singleton is used after main() completes.

Joe Gottman
Jul 22 '05 #8

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

Similar topics

7
12485
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) explicitly make the arbitrary class's constructor and destructor private b) declare the Singleton a friend of the arbitrary class
10
2662
by: E. Robert Tisdale | last post by:
Could somebody please help me with the definition of a singleton? > cat singleton.cc class { private: // representation int A; int B; public: //functions
1
2334
by: Spur | last post by:
Hi all, I implemented a memory allocation/deallocation class that logs all new/delete calls (overloaded) and remembers for each allocated block where it was allocated from (using a macro that passes __FILE__ and __LINE__). On destruction, it reports all undeleted blocks (memory leaks). The class is implemented in a separate .h/.cpp pair, and should be linked to
3
2505
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...
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
5317
by: Pelle Beckman | last post by:
Hi, I've done some progress in writing a rather simple singleton template. However, I need a smart way to pass constructor arguments via the template. I've been suggested reading "Modern C++ Design" or similar books, but I feel there are full of clever guys here who could help me out.
11
3188
by: tomgee | last post by:
I saw it many times, // T.h: class T { public: static T* instance(); private: T() {}
3
18269
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.
3
1809
by: stevewilliams2004 | last post by:
I am attempting to create a singleton, and was wondering if someone could give me a sanity check on the design - does it accomplish my constraints, and/or am I over complicating things. My design constraints/environment are as follows: 1) Everything is single-threaded during static initialization (as in prior to the open brace of main) 2) The environment may be multi-threaded during nominal program execution (within {} of main) 3) I...
0
9942
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
9792
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
11142
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
10848
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
9575
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
7972
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
5798
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
5992
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4614
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

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.