Is it possible to create a class which could be constructed just one time? If you would try to create an other instance of it, a compile-time error should occure.
-
4What you're looking for is called a singleton. en.wikipedia.org/wiki/Singleton_pattern I must urge you though to very seriously consider whether a singleton really makes sense for your application. 99% of the time a singleton is used, it should not be.Corbin– Corbin2012-04-28 08:33:22 +00:00Commented Apr 28, 2012 at 8:33
-
However, the singleton will just return the same instance for all creation queries. Probably this is even more useful that receiving exception.Boris Strandjev– Boris Strandjev2012-04-28 08:34:01 +00:00Commented Apr 28, 2012 at 8:34
-
AFAIK there is no option to make such class with compile time error. But there is a popular pattern called 'Singleton' for making such class that preventing instancing. You can easily google tons of examples.Dvoyni– Dvoyni2012-04-28 08:35:57 +00:00Commented Apr 28, 2012 at 8:35
-
@rafdp: Why do you want this? This smells like an XY Problem.johnsyweb– johnsyweb2012-04-28 08:46:28 +00:00Commented Apr 28, 2012 at 8:46
Add a comment
|
3 Answers
The classes with only one instances are called singleton classess,
There are many ways to perform that. The simplest is shown below
class MySingleton
{
public:
static MySingleton& Instance()
{
static MySingleton singleton;
return singleton;
}
// Other non-static member functions
private:
MySingleton() {}; // Private constructor
MySingleton(const MySingleton&); // Prevent copy-construction
MySingleton& operator=(const MySingleton&); // Prevent assignment
};
6 Comments
Dvoyni
rafdp asked for example of compile-time error, this is not an answer.
Jainendra
@Yarg If you will try to create more than one instances of class MySingleton then tis will give compilation error, this is what rafdp asked.
Dvoyni
How about
static MySingleton& OtherInstance() { static MySingleton anotherSingleton; return anotherSingleton; }Codie CodeMonkey
@Yarg If you are saying the class definition could be modified to create another instance, then of course. But I think the OP was talking about a scenario where the class was designed so that USERS of the class would get a compile error. I think it's reasonable to assume these users wouldn't modify the class to get around the restrictions.
Forever Learner
@Jaguar: The code is returning the reference. So there is no way to demonstrate compile time error.
MySingleton &a = MySingleton::Instance(); MySingleton &b = MySingleton::Instance(); Both a and b will be reference to the single static instance singleton |
Why compile error? You just need to implement Singleton design pattern, I think. Look here