Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an issue with this singleton implementation?

I've typically gotten used to implementing a singleton pattern in this manner because it's so easy:

class MyClass
{
    public:
        MyClass* GetInstance()
        {
            static MyClass instance;
            return &instance;
        }

    private:
        //Disallow copy construction, copy assignment, and external
        //default construction.
};

This seems significantly easier than creating a static instance pointer, initializing it in the source file, and using dynamic memory allocation in the instance function with guards.

Is there a downside that I'm not seeing? It looks thread-safe to me because I would think the first thread to get to the first line would cause the instantiation - and it seems nice and concise. I figure there has to be a problem I'm not seeing since this is not common though - I'd like to get some feedback before I keep using it

like image 835
John Humphreys Avatar asked Feb 10 '12 14:02

John Humphreys


People also ask

What is the problem with Singleton?

Singletons hinder unit testing: A Singleton might cause issues for writing testable code if the object and the methods associated with it are so tightly coupled that it becomes impossible to test without writing a fully-functional class dedicated to the Singleton.

What is the issue of Singleton design pattern?

They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases. They carry state around for the lifetime of the application.

What is one of the most common mistakes you can make when implementing a singleton?

A common mistake with that implementation is to neglect synchronization, which can lead to multiple instances of the singleton class.

What is common criticism of Singleton design pattern?

Select the correct answer: It does not allow lazy initialization It can not be thread-safe It is not object-oriented It introduces unnecessary global state into an application Give Feedback Submit.


1 Answers

This is not an inherent threadsafe solution: while constructing the instance, another thread can preempt and try to get the instance, resulting in either a double instance or in using an unconstructed instance.

This is handled by several compilers by adding a guard (in gcc, I think there is a flag to disable this) because there is no way to guard this with a userdefined mutex.

like image 77
stefaanv Avatar answered Sep 25 '22 03:09

stefaanv