Meyer’s singleton pattern calls constructor twice

  c++
// Meyer's singleton pattern
struct S {
  static S& GetInstance() {
    static S s;
    return s;
  }
}

// basic singleton pattern
Struct S {
  static S* s;
  static S& GetInstance() {
    if (s == nullptr) {
      s = new S();
    }
    return *s;
  }
}

I use Meyer’s singleton pattern but it call S() twice. To solve this problem. I have tried basic singleton pattern and It works. I provide this S class as shared library (like libS.so). there is any thing what I missed?

Edited

I added logging in constructor. like following. I noticed client reference different address

struct S {
  S() {
    std::printf("S constructor, address:%pn", this);
  }
}

And I use GCC5 version with std11. I have developed in multi-thread environment but We use scheduler to control only one thread run at the time.

Source: Windows Questions C++

LEAVE A COMMENT