I would like to have a class T that can generate only 1 instance in the whole program.
Now i know about std::unique_ptr but there are 2 problems:
- it’s limited to a scope ( but it’s not a big issue … )
- it needs to be explicitly used, meaning that it’s not part of the class or the type, it’s just and handler and a special pointer, but it does not modify the design of my class.
now i would like to have class T designed in a way that not even by mistake the user can declare 2 instances in the same program and i can’t rely on the fact that my user will declare an std::unique_ptr for T because i want to solve this by design.
right now i’m only thinking about how to make an implicit use of an unique_ptr in an elegant way, the problem is that i do not have any clue at the moment.
the other way around is to check if this class is handled by an unique_ptr but this check will make me lose an edge in terms of performances.
since having only 1 instance is really important, i see only 2 options in my case: 1) trying to solve this by design 2) throwing errors at compile time with some sort of check/macro.
I know that this looks trivial but with a design approach it’s not, at least for me, so please help.
What you’re looking for is called the Singleton pattern, and while it is widely considered by many (myself included) to be an anti-pattern, I will nonetheless show you the basic elements needed to build one.
Basically what you need to do is provide three things:
staticmethod which “gets” the one and only instanceprivateconstructor, so that nobody can ever instantiate itmainstartsHere’s the essential code:
I leave it to you to discover how to implement #3 above, and why you shouldn’t be using a Singleton in the first place — there are many reasons.