Singletons and destructors
Hi all.
I have struggled for a couple of days with a singleton pattern.
It turned out that the cause of the problem is that the destructor
of a singleton pattern is not called unless somebody calls a
'delete' to a pointer to the singleton.
Below is an example, where the program reports what methods
it calls. The only way I can find to see a report from the
singleton::destructor is to uncomment the 'delete' statement
indicated.
This is a bit awkward, since there may be more than one
refernece to the singleton, and it is not at all clear which
refernce should be burdened with the responsibility to
delet the singleton.
The obvious solution is to re-write the singleton pattern in
terms of smart pointers. I don't want to reinvent the wheel,
so is there a standard singleton pattern out there which
uses smart pointers?
Rune
///////////////////////////////////////////////////////////////
//#include "stdafx.h" // Uncomment if you use visual studio
#include <iostream>
class singleton{
public:
static singleton* instance();
~singleton();
protected:
singleton();
private:
static singleton* instance_;
};
singleton* singleton::instance_=0;
singleton::singleton()
{
std::cout << "In constructor" << std::endl;
}
singleton::~singleton()
{
std::cout << "In destructor" << std::endl;
}
singleton* singleton::instance()
{
std::cout << "In 'instance'" << std::endl;
if (instance_ == 0)
{
instance_ = new singleton;
}
return instance_;
}
int main(int argc,char* argv[])
{
singleton* s = singleton::instance();
singleton* t = singleton::instance();
// delete t; // <<< === Uncomment to call destructor
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]