In my project we have a few singletons, which tends to be problematic in unit tests. So I wanted to find solution for the problem. Here is what I came with so far:
smart_singleton.h
class smart_singleton
{
public:
static std::shared_ptr<smart_singleton> get_instance();
private:
smart_singleton();
smart_singleton(const smart_singleton&) = delete;
smart_singleton operator=(const smart_singleton&) = delete;
smart_singleton(smart_singleton&&) = default;
smart_singleton& operator=(smart_singleton&&) = default;
static std::weak_ptr<smart_singleton> weak_instance;
};
smart_singleton.cpp
std::weak_ptr<smart_singleton> smart_singleton::weak_instance;
std::shared_ptr<smart_singleton> smart_singleton::get_instance()
{
if (auto existing_instance = weak_instance.lock()) {
return existing_instance;
} else {
std::shared_ptr<smart_singleton> tmp_shared(new smart_singleton());
weak_instance = tmp_shared;
return tmp_shared;
}
}
smart_singleton::smart_singleton()
{
}
The difference is that you need to hold one shared_ptr from "get_instance()" anywhere in your code for the object to not be destroyed. In your prodution code that would be somewhere in the main function (or some object that is alive for the whole scope of main). In UT that would be for the duration of one test.
I would appreciate a feedback what flaws do you find in such a implementation