Stephan Born wrote:
Hello!
I do some experiments on shared_ptr and weak_ptr. So I tried to use them for a singleton-class, which does not need an explicit singleton::release_instance method. The singleton-instance will be destroyed everytime the last external shared_ptr holding the instance goes out of scope. Is this a valid usage for weak_ptr? Are there any traps I do not see using these smart_ptrs in this context?
Within the singleton class I hold the instance with a shared_ptr. I consider this the best option, as it guarantees the correct order of destruction when a singleton depends on another one.
The drawback of using shared_ptr with singleton is the need for a public destructor. But this is dangerous....it is possible to write
singleton::singleton_ptr first_ptr = singleton::instance(); delete first_ptr.get();
You should rely on the constructor that takes an additional deleter
argument, something like (not compiled and almost certainly incomplete
and incorrect):
class SingletonDeleter {
friend class shared_ptr<Singleton>;
operator() (Singleton *p) { delete p; }
};
class Singleton {
friend class SingletonDeleter;
public:
shared_ptr
Declaring the destructor as private is only possible when defining boost::checked_delete as friend of the singleton-class. [...] But then it is still possible to write the following code
singleton::singleton_ptr first_ptr = singleton::instance(); boost:checked_delete( first_ptr.get() );
OK, it's very unlikely to do it by chance, but it is possible.
Moreover, you rely on what should be an implementation detail. Cheers, Nicola Musatti