Singleton value not increasing

Hi,
I was testing something with singletons where I came across a behavior I'm not understanding.
I created a singleton class A. The object had an integer object initialized to 0. The value is expected to increase, on object creation to 1 and further every time I press a button.

Now, since the object is being created only once, I expected the print to be something like:
1
2
3
4
5

and so on, but what I got was:
1
2
2
2
2

I confirmed that the object is being created only once (using debugging), but I just don't understand this behavior. What am I be missing?

Please note that I'm using Qt API, and MainWindow::on_pushButton_clicked() is called every time I press a button while qDebug() works similar to a cout with a suffixed endl in this case.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  #include "MainWindow.h"
  #include "ui_MainWindow.h"
  #include "QDebug"

  class A{
  public:
      static A& getInstance()
      {
          static A *ins = new A;
          return *ins;
      }

      void print(){
          nPrintCntr = nPrintCntr + 1;
          qDebug() << nPrintCntr;
      }

  private:
      A()
      {
          nPrintCntr = 0;
          print();
      }
      int nPrintCntr;
  };

  MainWindow::MainWindow(QWidget *parent) :
      QMainWindow(parent),
      ui(new Ui::MainWindow)
  {
      ui->setupUi(this);
  }

  MainWindow::~MainWindow()
  {
      delete ui;
  }

  void MainWindow::on_pushButton_clicked()
  {
      auto x = A::getInstance();
      x.print();
  }
By just saying auto x you are creating a copy with initial value 1, then incrementing and printing that copy's value. Try auto& x instead.
Yep, that got it working. Thanks for the answer.
Topic archived. No new replies allowed.