3

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

asked Nov 28, 2013 at 7:38
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 Commented 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. Commented Nov 28, 2013 at 8:39

2 Answers 2

7

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());
answered Nov 28, 2013 at 7:55
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; }
};
answered Nov 28, 2013 at 8:01
1
  • Thanks, I didn't knew that. I have to try it out. Commented Nov 28, 2013 at 8:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.