views:

49

answers:

2

Let me explain it with an example: I have a class S, which is static.

I have two dynamic libraries A and B that use S.

I have an application, that links with A and B, in this application, how many different instances of S are created?

All this using C++ and in Ubuntu.

Thanks in advance

A: 

Both DLLs will use their own copy of the static variable.

ruslik
And if this variable is from another shared library? Therefore the libraries would be linked following a Diamond Pattern.How many copies would exist in the application of this static variable or Singleton class?
Victor
@Victor: It will be one copy per library that contains the code for *creating* the Singleton. So, if the code for creating it is in only one library, then you have only a single copy.
Bart van Ingen Schenau
A: 

I just ran some quick tests and it seems that if you use Meyer's singleton to provide access to S (SomeClass):

class SomeClass
{
public:
  static SomeClass& getInstance()
  {
    static SomeClass someClass;
    return someClass;
  }
 ...
};

there will be one instance of the global static variable under Linux i.e. shared among app and shared libs.

However AFAIR SomeClass needed to be contained in a DLL and not a static lib under windows: when SomeClass was part of a static lib I remember different instances flowing around in an application of mine and in my DLLs.

Ralf