c++ - How to ensure that there is at least one instance of a class? -
i need ensure there @ times during programm execution @ least 1 instance of class. singleton won't because (among other reasons) might in future need more instances. static class might feels going global... private members, both functions , variables.
i thought keeping shared_ptr somewhere safe, seems rough hack.
is there standard way this?
edit
to clarify: not matter of being able check whether instance still exists. instance must exist @ times. reason there static member variables in class, should maintain state.
i need ensure there @ times during programm execution @ least 1 instance of class.
so guess solution begins deciding responsible storing it.
you could: store internally within class (static) or return caller/client context (and rely on client context keep it). since "a singleton won't do" solution should this:
class theclass { public: // doesn't have std::shared_ptr<withcontext> // , shouldn't (see below) typedef <implementation-defined> globalcontext; globalcontext initcontext(); // return instance }; void main( /* ... */ ) { // before code uses theclass instances auto global_execution_context = theclass::initcontext(); // rest of application code goes here }
i thought keeping shared_ptr somewhere safe, seems rough hack.
what see it's drawbacks? if it's because it's obscure dependency, can add test it, or throw exception when context deleted/affected/not there. ask reference context in theclass' constructor.
the reason shouldn't have globalcontext std::shared_ptr it's own type, requirements amount to:
you need (new) type of object keeps common state of theclass between instances.
Comments
Post a Comment