Frage

I'm learning to use the Singleton design pattern. I wrote a simple code, include constructor overloading and a terminate function to delete the pointer. The problem is the constructor overloading doesn't work, it doesn't take 2 parameters. I can't figure out why?

//header============================================
#include <iostream>
using namespace std;

class singleton
{
public:
        static singleton* getInstance();
        static singleton* getInstance(int wIn,int lIn);
        static void terminate();// memmory management
        int getArea();// just to test the output


private:
        static bool flag;
        singleton(int wIn, int lIn);
        singleton();
        static singleton* single;
        int width,len;
};

//implement=============================
#include "singleton.h"
#include <iostream>

using namespace std;

int singleton::getArea(){
        return width*len;
}
singleton* singleton::getInstance(int wIn,int lIn){

        if (!flag)
        {
                single= new singleton(wIn,lIn);
                flag= true;
                return single;
        }
        else
                return single;
}

singleton* singleton::getInstance(){
        if (!flag)
        {
                single= new singleton;
                flag=true;
                return single;
        }
        else
        {
                return single;
        }
}

void singleton::terminate(){

        delete single;
        single= NULL;
        perror("Recover allocated mem ");
}


singleton::singleton(int wIn,int lIn){

        width= wIn;
        len= lIn;
}

singleton::singleton(){
        width= 8;
        len= 8;
}
//main=======================================
#include <iostream>
#include "singleton.h"

bool singleton::flag= false;
singleton* singleton::single= NULL;

int main(){

        singleton* a= singleton::getInstance();
        singleton* b= singleton::getInstance(9,12);
        cout << a->getArea()<<endl;
        //a->terminate();
        cout << b->getArea()<<endl;
        a->terminate();
        b->terminate();
        return 0;
}
War es hilfreich?

Lösung

in your main function you do

singleton* a= singleton::getInstance();

so the instance is set to the value the singleton got from the empty constructor. then you do

singleton* b= singleton::getInstance(9,12);

but you forgot that flag is true because you set it to true in the empty constructor. so this line is meaningless.

after that, everything you do on b is the same as it was if you did it on a, so it doesn't work as you wanted

Andere Tipps

The main() function interleaves the 'construction' and destruction of the singleton.

I'm not sure what you expected, but if the two pointers a and b were separated you would get a different output.

As it is both a and b point to the same object and so calls to getArea() will return the same result.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top