I'm maintaining some legacy code of a physical simulation. The calculation object is build as a singleton, to ensure there is only one instance. A co-worker told me, that singleton are completely out-of-date and I should instantiate it through a smartpointer. But I think it is not the same, because the initialization by a smartpointer doesn't garanties me, that there is only one instance of this object, right?
If I wanna have one single instance of an object in my code, which way is preferable:
To use the singleton pattern or the initialize the object through one of this smartpointers (auto_ptr<>
or unique_ptr<>
).
Best Answer
If you want to enforce that there is only a single instance of some class, then you must use the Singleton pattern. (aside from the question if your analysis is correct that you will only ever need a single instance.)
The C++ smart pointers
auto_ptr<>
andunique_ptr<>
enforce a completely different contract, namely that there is only one reference (or pointer) to a given instance.For example, this code is perfectly legal, but there are clearly two instances of
Resource
: