0

I have seen the classic singleton class in C++. My understanding is this implementation is thread safe. Then I read that if this class is included in 2 DLLs and both are loaded in 1 application, you will get 2 copies of static variable hence 2 instances of the S class, hence it is not exactly thread safe.

So the solution is still using a mutex lock? (I know this is common practice in C#, as detailed in : http://csharpindepth.com/Articles/General/Singleton.aspx

class S
{
    public:
        static S& getInstance()
        {
            static S    instance; 
            return instance;
        }
    private:
        S();
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement
};
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
user1866880
  • 1,437
  • 6
  • 18
  • 26

2 Answers2

3

A static variable's scope is its compilation unit.

If you have 2 dlls compiling 2 code blocks that contain that static member (or worse, you have it in a header....) then both dlls will be compiled with that variable.

No locks will change that fact.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
0

This is singleton code in C++

#include<iostream>
using namespace std;
class singletonClass
{


    static int i;
    static singletonClass* instance;
public:


    static singletonClass* createInstance()
    {


        if(i==0)
        {

            instance =new singletonClass;
            i=1;

        }

        return instance;

    }
    void test()
    {

        cout<<"successfully created instance";
    }
};

int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{


    singletonClass *temp=singletonClass::createInstance();//////return instance!!!
    temp->test();
}

Thanks

Tunvir Rahman Tusher
  • 6,421
  • 2
  • 37
  • 32