Re: singleton & auto_ptr (destructor is protected)
joycemenger wrote:
class Test {
protected:
Test() {}
~Test() {}
public:
static Test& Instance();
};
Test& Test::Instance() {
static auto_ptr<Test> instance( new Test );
return *instance;
}
Unfortunately, the tutorial didn't do a good job of explaining why
you'd want a protected destructor in a class such as Test. Basically,
you make the dtor protected to prevent client code from doing something
ill-conceived like:
Test* p = & Test::Instance();
delete p;
Of course, a wise and careful programmer would never write such a
thing, at least not in this simple form. But the more "careless"
mistakes that can be transformed into compile-time errors, the better.
Of course, now *nobody* can call delete on a pointer to Test (since
delete calls the dtor and the dtor is protected). There are two ways
to fix that. One (discussed in other posts in this thread) is to make
auto_ptr<Test> a friend of Test. Another is to use inheritance:
struct MyTest: Test {};
to create a class with a public destructor, which implicitly calls the
protected destructor of its base class. Inside the Instance()
function, write:
static std::auto_ptr<MyTest> instance ( new MyTest );
You still return a Test& to the client (which is accessible because
Test is a public base class of MyTest).
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]