Sign in to follow this  
ICUP

C++: Enforcing single object class

Recommended Posts

ICUP    140
What is the method to make sure that only one object can be instantiated for a class? I think I read this in my Effective C++ book but I can't seem to find it...

Share this post


Link to post
Share on other sites
fpsgamer    856
Singleton, or similarly a Monostate.

Be warned that both of those deign patterns are subject to rampant overuse (see: singletonitis). Searching for those terms on the forums will provide you with plenty of information.

Share this post


Link to post
Share on other sites
Hodgman    51222
Quote:
Original post by fpsgamer
Quote:
Original post by ICUP
What is the method to make sure that only one object can be instantiated for a class?
Be warned that both of those deign patterns are subject to rampant overuse (see: singletonitis).
To pre-empt the singleton hate that is bound to appear at any moment, can you tell us why you have to limit this class to only having one instance?

Share this post


Link to post
Share on other sites
jbadams    25674
The pattern you're probably thinking of is called a Singleton, although you may also actually want the somewhat similar Monostate.

This article on Singletons presents a brief discussion of the pattern as well as a checklist which may help you decide whether a Singleton is really what you need in your particular case; be sure that you really must (not just want to, but must) enforce single instantiation of the class in question and that you need global access. If you do decide that a Singleton or Monostate is appropriate for your situation then the article Singleton and Monostate (.pdf) might be a good read on the subject.

One of our moderators, Promit, has collected some excellent additional information on Singletons here, and I highly recommend at least the first three of his links (it's a brief series on the topic).

Share this post


Link to post
Share on other sites
Nitage    1107
There's a 3rd option - if you're wrapping an API that only allows you to create a single instance of something, just store a static instance count variable in the class and throw an exception if more then one is created.

This method has the advantage that it's really easy to refactor should creating 2+ instances of the class become possible/desirable.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this