lundi 30 octobre 2017

Singleton Derived Class with multiple bases of non-default constructors

I have a class derived from multiple base classes and I want to make it a singleton. Problem is the derived and base classes do not use default constructors and take arguments, so I'm confused how I can manage. I want to be able to pass the arguments to what would have been the constructor, but I only want possible to do once (I don't want it to be a setter). My only solution was a static bool value in the getInstance() member of the derived class.

Basic case:

//Singleton Derived Class with multiple bases of non-default constructors
class base1 {
    public:
        base1(int* value) :
              val_{value} {;}
        ~base1();
    private:
        int val_;
}

class base2 {
    public:
        base2(int* value) :
              val_{value} {;}
        ~base2();
    private:
        int val_;      
}

class derived : public base1, public base2 {
    public:
        derived(int* value) :
                base1{value},   //Base 1 constructor call
                base2{value},   //Base 2 constructor call
                val_{value} {;}
        ~derived();
    private:
        int val_;
}

//Creation
derived newDerived(&value);

Attempt to make it singleton-like?

//Lets make it a singleton
class base1 {
    public:
        base1(); //Can I pass the construtor anything?
        ~base1();
    private:
        int val_;
}

class base2 {
    public:
        base2(); //Can I pass the construtor anything?
        ~base2();
    private:
        int val_;      
}

class derived : public base1, public base2 {
    public:
        static derived& getInstance(int* value) {
            static bool init;
            if (!init) {
                base1::val_ = value;
                base2::val_ = value;
                init=true;
            }
            static derived instance;
            return instance;
        }
        derived(int* value) {;}
        ~derived();
    private:
        derived(derived const&) = delete;           //Copy construct
        derived(derived&&) = delete;                //Move construct
        derived& operator=(derived const&) = delete;//Copy assign
        derived& operator=(derived &&) = delete;    //Move assign
        int val_;
}

//Creation
derived::getInstance(&value);

I'm looking for some direction on how I should go about this, or maybe reasons I shouldn't do it at all? Thanks

Aucun commentaire:

Enregistrer un commentaire