Valid singleton class?

class Singleton
{
 private:
     static Singleton s;
     Singleton(){}
 public:
    static Singleton *getInstance()
    {
        return &s;
    }
};

Singleton Singleton::s;

Is this a valid singleton class?

class Singleton
{
 private:
     static Singleton *m_instance;
     Singleton(){}
 public:
    static Singleton *getInstance()
    {
        return m_instance;
    }

};
Singleton * Singleton::m_instance = new Singleton;

.

class Singleton
{
 private:
     static Singleton *m_instance;
     Singleton(){}
 public:
    static Singleton *getInstance()
    {
        if(m_instance == NULL)
        {
            lock();
            if(m_instance == NULL)
                m_instance = new Singleton;
            unlock();
        }
        return m_instance;
    }

};
Singleton * Singleton::m_instance = NULL;

The three singleton classes above both are thread safe, but they are both prone to a “static fiasco of initialization order”, am I correct?

+4
source share
3 answers

Is this a valid singleton class?

Now, after editing the answer “yes”, it is valid, and it is also thread safe, since all the static variables of the non-functional area are built before main(), while there is only one active thread.

C ++ Standard n3337 § 3.6.2 / 1 § 3.6.2 / 2: Initialization of non-local variables

: , (3.7.1) (3.7.2). . . .

(3.7.1) (3.7.2) (8.5) . :

- ( ), - (5.19), lvalue, (. 12.2);

- , constexpr, ( ), (7.1.5) mem- ;

- , , , .

, - ; . . (...)

++ n3337 § 6.7/4:

(8.5) (3.7.1) (3.7.2) . (3.6.2) , , , . , . ; . , , . , , *). (...)

*):

- .

. getInstance:

Singleton& getInstance()
{
    static Singleton instance;
    return instance;
}

.

?

++ 11 . ++ 03

pthread_once


, :

Singleton( Singleton const&);      // Don't Implement
void operator=( Singleton const&); // Don't implement
+6

, . .

Singleton , , , Singleton, , Singleton::s ( undefined). :

// in another compilation unit, far far away
struct Foo {
    Foo() {
        Singleton::getInstance();
    }
};
Foo foo;
+3

What a lazy initialized Singleton, yes. This is thread safety under C ++ 11.

0
source

Source: https://habr.com/ru/post/1534414/


All Articles