Re: Singletons / classes with only one member
On Feb 27, 12:30=EF=BF=BDpm, W Karas <wka...@yahoo.com> wrote:
Suppose you have a class that has only one instance, and
there is little reason to think it would ever make sense
for the class to have more than one instance. =EF=BF=BDWhat are
some criteria for deciding whether it should even be a
class?
The most important criteria is whether having more than one object of
the class would cause errors, or how important that constraint is.
Often I see programmers make a class a Singleton simply because they
cannot see any reason to have more than one object and want global
access to it. Rather than asking how likely it is that more than one
instance will exist, you should be asking if there would be any
problems with multiple instances existing.
[examples snipped]
The one obvious advantage of a class is that privacy is
strictly enforced by the compiler (as opposed to putting
private stuff in a sub-namespace that is private by
convention).
Putting the private stuff in an unnamed namespace in the implimation
file is a pretty strict enforcement of privacy.
The obvious advantage of a class is that one can make multiple
instances at a later date, with little modification.
The disadvantage of a class is the classic problem of
trying to minimize implementation details in the header
file for external code. =EF=BF=BDI'm aware of the technique of
using a pointer or reference to class private data, but
is it more trouble than it's worth? =EF=BF=BDIt seem generally
unintuitive to have a class of objects with only one
object in it.
What you describe is often called the "pimpl" idiom. I suggest that it
only be used to provide compiler firewalls. I have had times when
modifying a header file meant a 30 minute recompile, and the class'
privates were still quite volitile. In those cases, the pimpl idiom
makes a lot of sinse, but not as a matter of course.
The keyword "class" is pretty overloaded in C++ code. It is often used
to express interfaces, namespaces, and clumps of pure data as well as
the classical notion of Class. I suggest that in those situations
where some other keyword would work just as well, maybe it's a good
idea to use it.