As a consequence of the design of a framework I’m targeting with a plugin, I’ve implemented a part of my code as a singleton. This class is responsible for handling connections to an external program with which I’m communicating from within the framework.
Enabling the external communication is a runtime setting, however, and if it is disabled, I don’t want to allow access to it from models within the framework. I’ve implemented it using the version which is frequently recommended here:
class Communicator {
public:
static Communicator& getInstance() {
static Communicator instance;
return instance;
}
// ...
private:
static bool ServiceEnabled;
// Constructors, operator=, etc ...
}
Now, given that ServiceEnabled is false, I don’t want to allow getInstance to return a valid Communicator. But since I return a reference, I can’t simply return 0 or some such… What would proper behaviour be? Note that it is perfectly valid to continue execution even if ServiceEnabled is false, so I can’t just abort if it is.
Add a public function
and throw an exception in
getInstance, when it’s called while ServiceEnabled == false;