Re: Singletons and destructors
On Jul 23, 6:23 pm, Rune Allnor <all...@tele.ntnu.no> wrote:
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
delete the singleton.
The obvious solution is to re-write the singleton pattern in
terms of smart pointers.
Why call "new" to allocate the singleton in the first place? Wouldn't
the more obvious solution be to avoid "new" and "delete" by having the
singleton be statically - instead of dynamically - allocated? In fact,
the "classic" singleton pattern takes such an approach:
#include <iostream>
class singleton
{
public:
static singleton* instance();
~singleton();
protected:
singleton();
};
singleton::singleton()
{
std::cout << "In constructor" << std::endl;
}
singleton::~singleton()
{
std::cout << "In destructor" << std::endl;
}
singleton* singleton::instance()
{
static singleton instance_;
std::cout << "In 'instance'\n";
return &instance_;
}
int main(int argc,char* argv[])
{
singleton* s = singleton::instance();
singleton* t = singleton::instance();
// no delete singleton call
}
Program Output:
In constructor
In 'instance'
In 'instance'
In destructor
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]