2

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<>).

2
  • Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask
    – gnat
    Nov 28, 2013 at 7:47
  • 1
    Singletons are out of date, see this article. They are basically equivalent to global variables and have most of their disadvantages. But fixing that is not simple matter of using another tool. You need to switch to a different design pattern (usually dependency injection) and it requires some serious restructuring of the code.
    – Jan Hudec
    Nov 28, 2013 at 8:39

2 Answers 2

6

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<> and unique_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:

class Resource {
// ...
};

std::unique_ptr<Resource> instance1(new Resource());
std::unique_ptr<Resource> instance2(new Resource());
0
1

In C++ 11 the "singleton pattern" is just nothing more than a static variable inside a fucntion body:

If you want to prevent an object to be instantiated just do

class Object
{
private:
   Object() = default;
   Object(const Object&) = delete;
public:
   static Object& instance() { static Object z; return z; }
};
1
  • Thanks, I didn't knew that. I have to try it out.
    – Smii
    Nov 28, 2013 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.