Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!purdue!bu-cs!mirror!necntc!necis!mrst!sdti!wmm From: wmm@sdti.com (William M. Miller) Newsgroups: comp.lang.c++ Subject: Re: Allowing only one instantiation of a class Message-ID: <1989Oct19.004919.1070@sdti.com> Date: 19 Oct 89 00:49:19 GMT References: <672@suntops.Tops.Sun.COM> Reply-To: wmm@sdti.SDTI.COM (William M. Miller) Organization: Software Development Technologies, Inc. Lines: 31 In article <672@suntops.Tops.Sun.COM> rdas@hatter.Tops.Sun.COM (Robin Das) writes: > >How do you allow only one instantation of a class across a system? There are lots of ways. It really depends on what you want to do if some code attempts to violate the constraint. For example, if you want to detect unauthorized allocations at compile time, make the constructor private and then have a single "friend" function whose sole job is to allocate the single system-wide instance. That way, any code which tries to create an object of the restricted type will be flagged as illegal by the compiler. (If you think you need to, you can also put a static counter into the friend to make sure it is called only once, too.) If you want to generate a runtime error, you can put a static int member into the class and have the constructor increment it and complain if the count goes over 1 (static members of classes are shared among all instances and are initialized to 0 unless you say differently). If you want to allow multiple allocations and have them all refer to the same object, you can combine the two previously-mentioned approaches after a fashion: give the restricted class a private constructor and make an access class a friend. The friend will have a static pointer to the restricted class; its constructor will check the pointer and only allocate an instance if it is NULL. All references to the restricted class instance are made through the access class objects. -- Non-disclaimer: My boss and I always see eye-to-eye (every time I look in the mirror). ...!genrad!mrst!sdti!wmm