Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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

share|improve this question
    
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 '13 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 '13 at 8:39

2 Answers 2

up vote 5 down vote accepted

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());
share|improve this answer
    
Thanks a lot, you confirmed my assumption! –  Smii Nov 28 '13 at 8:00

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; }
};
share|improve this answer
    
Thanks, I didn't knew that. I have to try it out. –  Smii Nov 28 '13 at 8:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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