jeudi 27 avril 2017

Singleton Implementation: counter not incrementing as expected with multiple pointers to instance

The following program aims to instantiate and use the singleton pattern class proposed by Loki Astari and accepted as answer at the following link. C++ Singleton design pattern

Note the addition of a simple counter, by way of the private counter variable, along with the increment() mutator, and getCtr() accessor methods.

Expected program output is:

0
1
Press any key to exit...

The actual output is

0
0
Press any key to exit...

Why is the counter in the singleton class not being incremented as expected?

What follows is a minimal, complete, and verifiable program, written to illustrate the issue.

#include "stdafx.h"
#include <iostream>
#include <string>

class S {
public:
    static S & getInstance() {
        static S instance;
        instance.counter = 0; // initialize counter to 0
        return instance;
    }
    S(S const &) = delete;
    void operator = (S const &) = delete;

    void increment() { ++counter; }
    int getCtr() { return counter; }
private:
    S() {}
    int counter;
};

int main() {
    S * s; // s is a pointer to the singleton object
    S * t; // t is another pointer to the singleton object.

    std::cout << s->getInstance().getCtr() << std::endl;
    s->getInstance().increment(); // increment counter
    std::cout << t->getInstance().getCtr() << std::endl;

    std::cout << "Press any key to exit...";
    std::cin.get();
    return 0;
}

Thx, Keith :^)

Aucun commentaire:

Enregistrer un commentaire