mercredi 29 décembre 2021

How to construct several singleton objects?

I have a singleton, for example:

#include <bits/stdc++.h>

class A { 
 private:
  A() {printf("init a unparam A\n");}
  virtual ~A() = default;

 public:
  static A& Inst() { static A u; return u;} 
  void print() {printf("my no = %d\n", no_);}
  int no_ = -1;
};

I know this is odd; in most situations, I only need one in my program. However, in some cases, I need several objects in one program, so I added a constructor with an int parameter.

#include <bits/stdc++.h>

class A { 
 private:
  A() {printf("init a unparam A\n");}
  A(int i) : no_(i) { printf("init a A with no = %d\n", no_);}  // this part is added
  virtual ~A() = default;

 public:
  static A& Inst() { static A u; return u;} 
  static A& Inst(int i) { static A u(i); return u;}   // added
  void print() {printf("my no = %d\n", no_);}
  int no_;
};

In main.cpp:

int main() {
  A & a = A::Inst();
  a.print();
  A & b = A::Inst(1);
  b.print();
  A & c = A::Inst(2);
  c.print();
}

The result is:

init a unparam A
my no = 0
init a A with no = 1
my no = 1
my no = 1  // Inst(2) only get the Inst(1) object, why?

In my opinion, the first a will create a Inst by calling the no parameter constructor, b will create one with no=1, c create one with no=2.

But the real result is, b and c share one object.

Could you help on this? How can I make this work?

Aucun commentaire:

Enregistrer un commentaire