Private Destructor - Use

A

Amol

Hi
What is the use declaring a dtor as private?
In one of the design tips on net, it is said that this prevents
possibiltiy of creating automatic variable of the class. Is this true?
Can this concept work in a Singleton?
How memory leak can be avoided since delete can not be called because
dtor is private?

Thanks in advance
Amol
 
?

=?iso-8859-1?q?Erik_Wikstr=F6m?=

Hi
What is the use declaring a dtor as private?
In one of the design tips on net, it is said that this prevents
possibiltiy of creating automatic variable of the class. Is this true?
Yes

Can this concept work in a Singleton?
Yes

How memory leak can be avoided since delete can not be called
because dtor is private?

You have to create a special function that deletes instances of the
class, this can either be a static function or a member function. If I
were to use this I would make the constructor private too.

class Test
{
int i_;
~Test() {}
Test(int i) : i_(i) {}
public:
static Test* create(int i)
{
return new Test(i);
}
static void del(Test* t)
{
delete t;
}
};

int main()
{
Test* t1 = Test::create(4);
Test::del(t1);

Test* t2 = new Test(4); // Does not work
Test t3(4); // Does not work either
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,509
Members
48,195
Latest member
Tomjerry

Latest Threads

Top